php - 如何在函数php中向数组添加元素

标签 php arrays global-variables

如果数组中不存在元素,如何从函数内部向全局数组添加元素?

我的主代码会多次调用函数。但是每次都会在函数内部创建不同的元素

我的示例当前代码是,

$all=[];
t(); // 1st call
t(); //2nd call
function t(){
$d='2,3,3,4,4,4';  //this is a sample.but element will different for each function calling
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
  array_push($all, $e);
       }
     }
}
 print_r($all);

输出为空,

Array()

但我需要这样的

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)

谢谢

最佳答案

如果您查看 PHP 中的变量范围 http://php.net/manual/en/language.variables.scope.php 您会看到函数无法访问外部范围。

因此您需要通过引用传递数组:

函数 t(&$myarray)

在函数内部创建一个数组并返回那个数组

function t(){
  $all = [];
  $d='2,3,3,4,4,4';
  $d=explode(',',$d);
  foreach($d as $e){
    if(!in_array($e,$all)){
       array_push($all, $e);
    }
  }
return $all;

}

或者如果你想继续添加到数组中,你可以这样做

function t($all){
  $d='2,3,3,4,4,4';
  $d=explode(',',$d);
  foreach($d as $e){
    if(!in_array($e,$all)){
       array_push($all, $e);
    }
  }
return $all;
}

然后调用函数 $all = t($all);

关于php - 如何在函数php中向数组添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787767/

相关文章:

arrays - 使用泛型类型定义的函数

javascript - 通过公共(public)键对对象数组进行分组,将嵌套属性合并到数组中

c - STM32 C 中的全局变量

python - 为什么可以在主作用域中声明且不是全局的函数中使用变量

iphone - 单例类iPhone

php - MySql INSERT 与 PHP file_put_contents

php - 如何在不使用 Bootstrap 的情况下获得相同的结果?

php - PHP 中具有不透明度的径向渐变

php - 如何在 PHP 中使用 flock?

javascript - 使用要查找的键数组和要替换的数组值来查找和替换