0

我如何找到数组中元素的长度,以确保每个元素的长度超过 2 个字符。使用 php 是...

前任。$this_array=array ("this", "and", "this", "and", "th")

4

5 回答 5

2

循环可能有点矫枉过正,除非您需要做的更多 - 过滤更有效。

<?
$this_array =  array("a", "this", "and", "this", "and", "th");

$this_array = array_filter($this_array, function($val){return strlen($val)>=2;});

print_r($this_array); // Array ( [1] => this [2] => and [3] => this [4] => and [5] => th )

注意:这只适用于 PHP 5.3+

于 2012-07-27T05:01:21.427 回答
1
foreach($this_array as $value) {
   $strlen = strlen($value);
   if($strlen <= 2)
   {
     echo '$value is '.$strlen.' characters long<br />';   
     // do something with it
   }
}
于 2012-07-27T05:00:50.117 回答
1
foreach ($this_array as $key => $value)
{
    if (strlen($value) < 3)
    {
        echo "{$value} is too short<br />";
    }
}

foreach

于 2012-07-27T05:00:17.027 回答
1
foreach($this_array as $val) {
   $valLength = strlen($val); //gives length 
   if($valLength < 3) {
       //something here, less than 2 char
   } 
}
于 2012-07-27T04:59:24.517 回答
0
$this_array=array ("aa", "bb", "cc", "asd", "aa");    



function lengthCheck($v, $w)
    {
     global $lengthOK;
       $len=  strlen($w);
       if($len<3)
       {
        $lengthOK=false;
       }
        return $lengthOK;
    }


    $lengthOK=true;// set everytime when you call "lengthCheck"
    $b = array_reduce($this_array, "lengthCheck");

    var_dump($b);

$b 将具有 true/flase。即,如果所有元素的长度都为 3 或更长,则为 TRUE,否则为 false。

于 2012-07-27T05:05:30.060 回答