如何在php函数中向数组添加元素
如果数组中不存在元素,如何从函数内部向全局数组添加元素 我的主代码将多次调用函数,但每次都会在函数内部创建不同的元素 我的示例当前代码是如何在php函数中向数组添加元素,php,arrays,global-variables,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
$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
)
谢谢您的代码将显示错误,因为$all不在函数的作用域内,您需要传入该值才能生效
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$all=[];
t($all); // 1st call
t($all); //2nd call
function t( &$data){
$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,$data)){
array_push($data, $e);
}
}
}
print_r($all);
您可以使用global,但通常不鼓励这样做。如果您查看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)调用函数代码>添加Alexy关于使用“array_unique($d)”的回复,我建议这样做,因为它不需要循环。您可以将过滤后的数组传递给array_值($d),以便按照您想要实现的结果对元素进行索引。仅供参考:数组_unique将保留原始密钥:
您的案例需要删除重复项几次,最好有一个单独的功能:
$all = [];
function t(){
global $all;//Tell PHP that we are referencing the global $all variable
$d='2,3,3,4,4,4';
$d=explode(',',$d);
$d=rmvDuplicates($d);
$all = array_merge($all,$d);//Combine the new array with what we already had
$all = rmvDuplicates($all);
}
function rmvDuplicates(array){
$array=array_unique($d);
$array=array_values($d);
return $array;
}
我认为最好使用$all=array\u unique($d)
而不是这个foreach
实际上我需要忽略重复的元素。这不是一个处理它的好方法,但是你可以通过使用变量$all的全局关键字来实现,如下所示:function t(){global$all;…}
$all = [];
function t(){
global $all;//Tell PHP that we are referencing the global $all variable
$d='2,3,3,4,4,4';
$d=explode(',',$d);
$d=rmvDuplicates($d);
$all = array_merge($all,$d);//Combine the new array with what we already had
$all = rmvDuplicates($all);
}
function rmvDuplicates(array){
$array=array_unique($d);
$array=array_values($d);
return $array;
}