php: pushing to an array that may or may not exist

2019-04-21 12:10发布

I want to create an array with a message.

$myArray = array('my message');

But using this code, myArray will get overwritten if it already existed.

If I use array_push, it has to already exist.

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

Otherwise, it will bink.

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

5条回答
Anthone
2楼-- · 2019-04-21 12:34

Check if the array exists first, and if it doesn't, create it...then add the element, knowing that the array will surely be defined before hand :

if (!isset($myArray)) {
    $myArray = array();
}

array_push($myArray, 'my message');
查看更多
Juvenile、少年°
3楼-- · 2019-04-21 12:37

Here:

$myArray[] = 'my message';

$myArray have to be an array or not set. If it holds a value which is a string, integer or object that doesn't implement arrayaccess, it will fail.

查看更多
Deceive 欺骗
4楼-- · 2019-04-21 12:38

OIS' way will work.

Or

if (!isset($myArray)) 
    $myArray=array();
array_push($myArray, 'message');
查看更多
贪生不怕死
5楼-- · 2019-04-21 12:39

You should use is_array(), not isset. Usefull if myArray is being set from a function that returns an array or a string (-1 on error for example)

This will prevent errors if myArray is declared as a not an array somewhere else.

if(is_array($myArray))
{
   array_push($myArray,'my message');
}
else
{
   $myArray = array("my message");
}
查看更多
叛逆
6楼-- · 2019-04-21 12:41
if ($myArray) {
  array_push($myArray, 'my message');
}
else {
  $myArray = array('my message');
}
查看更多
登录 后发表回答