(array)$someemptyvariablethatisnotarray
returns array([0] =>)
instead of array()
How can I make it so I get a empty array that is not iterated when I'm using it inside foreach() ?
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.
For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.
1) Assigning it to a new empty array This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.
is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .
The feature which you are using, is called "casting". This means a variable is forced to become a given type, in your example an array. How the var is converted is not always obvious in PHP!
In your example $someemptyvariablethatisnotarray becomes an array with one entry with a NULL value.
The PHP documentation says:
The behaviour of an automatic conversion to array is currently undefined.
To solve your code I would recommend something like this:
if (!is_array($someemptyvariablethatisnotarray) {
$someemptyvariablethatisnotarray = array();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With