user1510648
user1510648

Reputation: 71

Can Indexed Arrays be used as associative arrays?

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

Answers (3)

Stegrex
Stegrex

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:

  1. PHP arrays are all associative; keys can be strings, or if not explicitly set, will be integers.
  2. Associative arrays are in the form of key => value pairs. If you have a key, you can find the value associated with it.
  3. When trying to get a value from a PHP array, the syntax is: $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

Marcus Johansson
Marcus Johansson

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

raina77ow
raina77ow

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

Related Questions