Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - empty array

(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() ?

like image 877
Alex Avatar asked Mar 24 '11 15:03

Alex


People also ask

How do I create an empty array in PHP?

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.

Is empty array falsey PHP?

For example, in PHP, empty arrays are falsy, but in JavaScript arrays are always truthy.

How do you create an empty array?

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 or empty PHP?

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 .


1 Answers

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();
}
like image 104
powtac Avatar answered Oct 06 '22 21:10

powtac