1

On running the following code I get output as true. Can anyone explain me the concept of this as I am new in PHP and getting very confused with it.

$foo = array(
     true, 
     '0' => false,
     false => true
);
0

1 Answer 1

3

Remember that array keys can only be integer or string values, and that string keys containing only digits are automatically converted to integer.... as per the PHP documentation

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

◦ Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
◦ Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
◦ Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
◦ Null will be cast to the empty string, i.e. the key null will actually be stored under "".
◦ Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

So for your example:

$foo=array(true,'0'=>false,false=>true);
  1. So the first entry you create with a value true is autoassigned a key 0.

  2. The second entry that you give key '0' and value false is converted to an integer key 0, and overwrites the first entry with the value false

  3. The third entry has a Boolean false for the key, which is typecast to integer 0, and so overwrites the existing entry again with its value of true.

You end up with a single element in your array, index of integer 0 and a value of true

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.