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]); }
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With