swapnesh
swapnesh

Reputation: 26732

Why null key change value to 1 in php array?

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 -

  1. 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.
  2. At second value 1 is blank however it was supposed to be 1.
  3. 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.

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

Answers (3)

dev-null-dweller
dev-null-dweller

Reputation: 29482

You are using print_r, it makes your output readable so:

  1. NULL key is overwritten from "swapnesh" to true, printable representation of true is 1
  2. NULL and false does not produce output in printable format.
  3. Count is 4 because you are overwriting 2 keys.

To get better output of variables, use var_dump

Upvotes: 3

Nick Pickering
Nick Pickering

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

deceze
deceze

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

Related Questions