0

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"  
PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
Saif
  • 2,530
  • 3
  • 27
  • 45
  • And where are you stuck? What have you tried? – Ja͢ck Jun 08 '15 at 08:05
  • See also [this question](http://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php) and [this question](http://stackoverflow.com/questions/10474216/php-how-to-filter-an-array-that-contains-something). – Ja͢ck Jun 08 '15 at 08:13
  • Thank you, its working. @Ja͢ck – Saif Jun 08 '15 at 08:19

2 Answers2

10

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

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • 1
    it wasn't me that downvoted, but in your output the indexes go like 0,1,3,4 instead of 0,1,2,3 like requested. Therefore I used `array_values` after `array_filter`. – n-dru Jun 08 '15 at 08:54
  • Thanks for that I'll make some changes to accomplish that thanks @n-dru – Narendrasingh Sisodia Jun 08 '15 at 08:56
  • Thank you for your effort but Jack's code is working for me. `$array = array_values(array_filter($array, function($v) { return strlen($v) > 4;` – Saif Jun 08 '15 at 08:57
  • @SaifUrRahman I've another answer too in which your key indexes will be as you needed and I appreciate that answer too – Narendrasingh Sisodia Jun 08 '15 at 08:59
  • I just need the keys to be auto adjusted, when the elements are removed. – Saif Jun 08 '15 at 09:01
5

Use array_filter and then array_values to reset the keys sequence:

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

Output:

Array ( [0] => Linda [1] => Chadwick [2] => Angela [3] => Marco ) 
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
n-dru
  • 9,285
  • 2
  • 29
  • 42
  • `"; $c=count($array); echo "NUMBER OF ELEMENTS:".$c; echo "
    "; for($i=0;$i<$c;$i++) { echo "INDEX".$i."="; echo $array[$i]; echo "
    "; } $array = array_values(array_filter($array, function($v){if(strlen($v)>4){return $v;}})); echo "AFTER:"; echo "
    "; $c=count($array); echo "NUMBER OF ELEMENTS:".$c; echo "
    "; for($i=0;$i<$c;$i++) { echo "INDEX".$i."="; echo $array[$i]; echo "
    "; } ?>`
    – Saif Jun 08 '15 at 08:08