Devon Bessemer
Devon Bessemer

Reputation: 35337

php array with a variable that doesn't create a key

I have a function that accepts an array as an argument, then another function that uses this. In the second function, I have the array created using a variable, but some values should only create an empty array. Do I have to add a check or is there a value that can go inside an array and NOT make a key?

For instance:

array() = no key made

array(null) = key made 0 =>

array('') = key made 0 =>

array(0) = key made 0 => 0

So if I have an array created like array($value). Is there any way to have $value represent nothing? There is an easy enough workaround with a check, but it was curiosity that led me to ask whether this is possible.

Upvotes: 0

Views: 51

Answers (3)

Diptendu
Diptendu

Reputation: 2158

To support @dave's answer - Taken from PHP manual

    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.

So whatever value you pass to the array() method it will map to one of these types and a non empty array will be created with appropriate value.

Upvotes: 1

tkausl
tkausl

Reputation: 14269

There is no way to put something into an array and have nothing in it. I don't understand what you really trying to do but an empty array is just

$emptyarray = array(); //Old
$emptyarray = []; //New

There is also no way to put something in an array without a key. If it is in the array, then you can (have to) reference it somehow.

Upvotes: 0

dave
dave

Reputation: 64657

No there is not - if you pass an argument to the array constructor, the array will contain an element.

Upvotes: 1

Related Questions