如果数组中不存在元素,如何从函数内部向全局数组添加元素?
我的主代码会多次调用函数。但是每次都会在函数内部创建不同的元素
我的示例当前代码是,
$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/