Äsi*_*mäl 4 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);
Run Code Online (Sandbox Code Playgroud)
输出为空,
Array()
Run Code Online (Sandbox Code Playgroud)
但我需要这样
Array
(
[0] => 2
[1] => 3
[2] => 4
)
Run Code Online (Sandbox Code Playgroud)
谢谢
小智 5
如果您查看 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;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你想继续添加到数组中,你可以这样做
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;
}
Run Code Online (Sandbox Code Playgroud)
然后调用该函数$all = t($all);