Php: clicking on an array that may or may not exist

I want to create an array with a message.

$myArray = array('my message'); 

But using this code, myArray will be overwritten if it already exists.

If I use array_push , it should already exist.

 $myArray = array(); // <-- has to be declared first. array_push($myArray, 'my message'); 

Otherwise, he will deceive.

Is there a way to do the second example above without first clearing $myArray = array(); ?

+7
arrays push php declaration
source share
5 answers

Check if the array exists first, and if not, create it ... then add the element, knowing that the array will definitely be defined in advance:

 if (!isset($myArray)) { $myArray = array(); } array_push($myArray, 'my message'); 
+5
source share

Here:

 $myArray[] = 'my message'; 

$ myArray must be an array or not set. If it contains a value that is a string, an integer, or an object that does not implement arrayaccess, it will fail.

+27
source share

You should use is_array (), not isset. Useful if myArray is set from a function that returns an array or string (e.g. -1 on error)

This will prevent errors if myArray is declared as not an array elsewhere.

 if(is_array($myArray)) { array_push($myArray,'my message'); } else { $myArray = array("my message"); } 
+3
source share
 if ($myArray) { array_push($myArray, 'my message'); } else { $myArray = array('my message'); } 
0
source share

OIS will work.

or

 if (!isset($myArray)) $myArray=array(); array_push($myArray, 'message'); 
0
source share

All Articles