繁体   English   中英

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

[英]how to add elements to an array inside a function php

如果元素不存在于数组中,如何从函数内部向全局数组添加元素?

我的主代码将多次调用函数。但每次在函数内部创建不同的元素

我的示例当前代码是,

$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);调用函数$all = t($all);

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

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

添加关于使用'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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM