php:推送到可能存在或可能不存在的数组 [英] php: pushing to an array that may or may not exist

查看:70
本文介绍了php:推送到可能存在或可能不存在的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用消息创建一个数组.

I want to create an array with a message.

$myArray = array('my message');

但是使用此代码,myArray将被覆盖(如果已存在).

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

如果我使用array_push,它必须已经存在.

If I use array_push, it has to already exist.

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

否则,它将合并.

是否有一种方法可以使上面的第二个示例正常工作,而无需先清除$myArray = array();?

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

推荐答案

检查数组是否首先存在,如果不存在,则创建它...然后添加元素,知道该数组肯定会在之前定义手:

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

这篇关于php:推送到可能存在或可能不存在的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆