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
without array_values
Repl - array_filter
using array_values
on the returned array of array_filter
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.