Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(bool)true var does not get converted to array on array assignment, but (bool)false does. Why?

Tags:

arrays

php

Using PHP... an example. This produces a warning - as expected - and $myVar stays as bool(true).

$myVar = true;
$myVar[] = 'Hello';  // Warning: Cannot use a scalar value as an array

But this next example 'works', $myVar is converted into an array with a single element 'Hello'.

$myVar = false;
$myVar[] = 'Hello';  // Converted into an array

Results in:

array(1) {
  [0]=>
  string(5) "Hello"
}

Yet both bool(true) and bool(false) are both scalar. So why the difference? What rule in PHP governs this behaviour? Or is it 'just the way it is'?!

I initially thought it might be to do with type casting rules, but both bool(true) and bool(false) behave the same in this respect.

Thanks.

like image 869
MrWhite Avatar asked Jan 22 '23 18:01

MrWhite


1 Answers

So, even though I don't know why PHP does that, I looked at some Zend code and can at least tell you where you can find out how exactly PHP does it.

So, the important code is in zend_fetch_dimension_address.

So, let's cover the above cases:

If it IS_ARRAY - everything obvious.

If it IS_OBJECT throw error unless it has ArrayAccess.

If it IS_STRING throw an error, unless the strings length is zero.

If it IS_NULL create a new array.

If it IS_BOOL throw an error, unless it is false.

Otherwise, throw an error.

So, this confirms your and my tests:

Error if object, non-empty string, true and other scalars, i.e. long and double. No error if array, empty string, null and false. So basically it does an automatic cast on most (but not all) "falsy" values.

like image 197
NikiC Avatar answered Jan 25 '23 23:01

NikiC