字符串变量末尾的[]是什么? [关闭]

I have a piece of PHP that I am currently porting to Objective-C. Although there is one function that I cannot figure out what it does. More specifically the square brackets [ ] on the end of the $hash2 variable. $hash2 is a sha256 variable and $i == 64.

$hash2[$i];

It means, the variable is considered as an array. The brackets let you define the index values.

You can learn more about that in the php manual.

On the other hand, if the variable is indeed a string, then it will access the n-th character of that string.

That gets a value from an array based on index, as far as I'm aware. In pseudo-php:

$arr = array("example" => 1,
             "other" => 2,
             3 => 3);

$arr["example"] == 1; // true
$arr[3] == 3; // true

Strings are just character arrays, so operating this on a string would get the character at that index:

$string = "This is a sample";
echo $string[3]; // Prints "s".

In PHP you can use array indexing on string values, so $string[64] would get the 65th character (it is zero based)

Access the value of the array at that offset. Some pseudo code:

array hash2;

hash2.get(i)

This is equivalent to the following PHP:

<?php

$hash2 = [];

echo $hash2[$i]

?>

If it is a string and not an array, you access the *i*th character within that string. This is because strings are internally character arrays (something you know from C).

<?php

$str = "Stackoverflow";

echo $str[2]; // t

?>