Reputation: 71
I know that in PHP an indexed array that looks like:
$array = ("hello", "world")
is the same as an associative array that looks like:
$array = (0 => "hello", 1 => "world");
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
my thinking is that it translates to
$hello = $array[0]
, which will equal
$hello = "hello"
. In other words, will
$array["hello"]
equal 0?
Upvotes: 0
Views: 71
Reputation: 4024
Let's walk through the thinking:
$array = ("hello", "world") // This is implicitly indexed by integer.
is the same as:
$array = (0 => "hello", 1 => "world"); // Explicit indexing.
You can verify by doing print_r($array)
; In either case, the output would show an indexed array. PHP arrays are all associative. Even if you did not specify a key, the values in an array are ordered by integer index numbers.
Now let's take a look at:
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
This is where the code will break. Why?
$array["hello"]
is not a valid value. What this is referencing is "the value of the array's list at index "hello".
However, array("hello", "world")
does not have an index key of "hello". Rather, it has a value "hello" which has implicitly the key index 0.
Make sure to read up on PHP arrays and understand that:
$array['key']
or in the case of multidimensionals $array['firstlevelkey']['secondlevelkey']
etc. The value that gets returned would be the value of the key => value pair at that particular key.I hope this is helpful!
Upvotes: 1
Reputation: 2667
No, since "hello" is not a valid key in $array.
You can check if a key exist using array_key_exists(key,*array*)
Upvotes: 0
Reputation: 106443
No, you cannot fetch a key of some array element by its value right away... unless you switch keys and values with array_flip:
$arr = array('hello', 'world');
$arr = array_flip($arr);
print $arr['hello']; // 0
Upvotes: 1