Search code examples
phparraysunsetstrlenarray-unset

Remove array element based on its character length


I have an array in PHP as:

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

Therefore,

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

I want to remove the names having string length <=4.

So that, the keys are adjusted.

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

Solution

  • You can simply use it using array_filter only along with strlen

    $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