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

╄→гoц情女王★ 提交于 2019-12-05 02:49:55

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');
OIS

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.

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");
}
if ($myArray) {
  array_push($myArray, 'my message');
}
else {
  $myArray = array('my message');
}

OIS' way will work.

Or

if (!isset($myArray)) 
    $myArray=array();
array_push($myArray, 'message');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!