Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove from array any string with 1 character?

So if you have an array:

$ourArray[0] = "a";
$ourArray[1] = "bb";
$ourArray[2] = "c";
$ourArray[3] = "ddd";

Is there an shorter way to remove all of the single character values from array than running array through a foreach statement and checking each one individually?

Or is this the quickest/best way to do this task?:

foreach( $ourArray as $key => $value){
    if(strlen($value) == 1){ unset($ourArray[$key]); }
}
like image 681
John Avatar asked Dec 24 '22 04:12

John


1 Answers

You can use array_filter to achieve this,

$arr = [
  'test',
  '1',
  'g',
  'test-two'
];

var_dump(array_filter($arr, function ($v) {
  return strlen($v) > 1;
}));

If you want to ensure blank spaces are accounted for then use trim on the value before strlen is used.

Note: The key formation will get ruined so you can reorganise them with array_values.

Live Example

Repl - array_filter withoutarray_values

Repl - array_filter using array_values on the returned array of array_filter.

like image 108
Script47 Avatar answered Dec 25 '22 16:12

Script47