如果数组中不存在元素,如何从函数内部将元素添加到全局数组中?
我的主代码将多次调用函数,但是每次在函数内部创建不同的元素
我当前的示例代码是
$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中查看变量作用域,您会发现函数无法访问外部作用域。
因此,您需要通过引用传递数组:
function 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句