简体   繁体   English

如何从数组中删除任何包含1个字符的字符串?

[英]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? 是否有更短的方法从数组中删除所有单个字符值,而不是通过foreach语句运行数组并单独检查每个值?

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, 您可以使用array_filter来实现此目的,

$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. 如果要确保考虑空格,则在使用strlen之前对值使用trim

Note: The key formation will get ruined so you can reorganise them with array_values . 注意:键形成将被破坏,因此您可以使用array_values重新组织它们。

Live Example 实例

Repl - array_filter without array_values Repl - 没有array_values array_filter

Repl - array_filter using array_values on the returned array of array_filter . Repl - array_filter在返回的array_filter数组上使用array_values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM