Reputation: 26732
Following is the code I am testing -
<?php
error_reporting(E_ALL);
$myarr = array(NULL => "swapnesh", TRUE => 1, 4 => "swap", "swap" => 4, TRUE => NULL, NULL => TRUE );
echo "<pre>";
//var_dump($myarr);
print_r($myarr);
echo count($myarr);
This code outputs -
Array
(
[] => 1
[1] =>
[4] => swap
[swap] => 4
)
4
Concerns/queries regarding the code -
Search involved before asking -
On php net I checked the doc and found this is something related but cant figured out much in my case. Link - http://php.net/manual/en/language.types.array.php
EDIT For the 3rd point I believe TRUE & NULL is used twice so ie its outputting 4 however let me know if it is exactly the case or not.
Upvotes: 2
Views: 642
Reputation: 29482
You are using print_r
, it makes your output readable so:
"swapnesh"
to true
, printable representation of true
is 1NULL
and false
does not produce output in printable format.To get better output of variables, use var_dump
Upvotes: 3
Reputation: 3185
Why NULL as a key change value to 1 (at first index) I can consider a scenario when someone may suggest since NULL as a key is used twice so value overwritten but I checked it with FALSE so it must output 0 but no value output in this case.
PHP prints the boolean FALSE as an empty string. Typecast it into an int to get '0'.
At second value 1 is blank however it was supposed to be 1.
TRUE is used as a key twice also, so its value is getting overwritten to NULL, which prints as empty string.
Count is 4 what I was thinking of either 5 or 6 but for 4 I am not sure how it is as last two values skipped.
Your count is lower because your last two values in the array are overwriting existing values in the array.
Upvotes: 1
Reputation: 522500
null
and true
are not valid keys. Keys can be either strings or integers. null
and true
are cast to an empty string and 1
respectively, which means you have several empty string/1
keys which overwrite each other.
If you want automatically indexed keys, leave the key off:
$myarr = array("swapnesh", 1, 4 => "swap", "swap" => 4, null, true);
Upvotes: 0