根据字符长度删除数组元素

时间:2015-06-08 07:27:06

标签: php arrays unset strlen array-unset

我在PHP中有一个数组:

$array = array("Linda","Chadwick","Bari","Angela","Marco");

因此,

 $array[0]="Linda"  
 $array[1]="Chadwick"  
 $array[2]="Bari"  
 $array[3]="Angela"  
 $array[4]="Marco"  

我想删除字符串长度为<=4的名称。

这样,键就被调整了。

$array[0]="Linda"
$array[1]="Chadwick"  
$array[2]="Angela"  
$array[3]="Marco"  

2 个答案:

答案 0 :(得分:5)

您只需使用array_filterstrlen

一起使用即可
$array = array("Linda","Chadwick","Bari","Angela","Marco");
$result = array_filter($array,function($v){ return strlen($v) > 4; });
print_r($result);

$result = array();
array_walk($array,function($v) use (&$result){ if(strlen($v) > 4){$result[] = $v;} });
print_r($result);

array_filter

array_walk

答案 1 :(得分:2)

使用array_filter然后array_values重置按键序列:

$array = array("Linda","Chadwick","Bari","Angela","Marco");
$array = array_values(array_filter($array, function($v) {
    return strlen($v) > 4;
}));
print_r($array);

输出:

Array ( [0] => Linda [1] => Chadwick [2] => Angela [3] => Marco )