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

时间:2018-02-14 12:54:43

标签: 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
)

谢谢

3 个答案:

答案 0 :(得分:2)

如果你看一下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);

调用该函数

答案 1 :(得分:0)

您的代码会显示错误,因为$ 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);

结果

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

您可以使用全局,但通常不鼓励这样做。

答案 2 :(得分:0)

添加关于使用'array_unique($ d)'的Alexy的回复,我推荐它,因为它消除了对循环的需要。您可以将已过滤的数组传递给array_values($ d)以索引元素,如您要实现的结果所示。仅供参考:array_unique将保留原始密钥:http://php.net/manual/en/function.array-unique.php

您的案例需要删除重复项次数,以便为其创建单独的函数:

$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;
}