验证数组中每个字符串的长度

时间:2019-02-08 17:22:51

标签: php arrays

我想验证一下,如果其中一个字符串的长度大于40,则回显“此数组包含一个长度大于40的字符串”。因此,在这种情况下,索引[11]包含的字符串长度大于40。我该怎么做?

array(5) {
  [0]=>
  string(19) "PEDRO MOACIR LANDIM"
  [1]=>
  string(19) "ADIR JOAO GASTALDON"
  [2]=>
  string(18) "ABEL PEDRO MARQUES"
  [10]=>
  string(28) "ADRIANO CESAR GARCIA JOAQUIM"
  [11]=>
  string(44) "AUTO VIAÇÃO CATARINENSE LTDA - FLORIANÓPOLIS"
}

3 个答案:

答案 0 :(得分:0)

foreach ($array as $key => $value) {
 if(mb_strlen($value) > 40){
  echo "this array contain a string wich lenght is greater than 40: ".$key;
 }
}

答案 1 :(得分:0)

由于如果大于40只需要检测其中一个字符串,则最好在遇到大于40的数字时中断循环。如果次数不在数组的最后一个索引处,则可以减少for循环执行的迭代次数。

foreach ($array as $arr) {
 if(mb_strlen($arr) > 40){
  echo "this array contain a string wich length is greater than 40";
  break;
 }
}

答案 2 :(得分:0)

您可以这样做:

<?php

    $myStrings = array(

    0 => "PEDRO MOACIR LANDIM",
    1 => "ADIR JOAO GASTALDON",
    2 =>  "ABEL PEDRO MARQUES",
    10 =>  "ADRIANO CESAR GARCIA JOAQUIM",
    11 => "AUTO VIAÇÃO CATARINENSE LTDA - FLORIANÓPOLIS"
    );

    foreach($myStrings as $key => $string){

    //Get length of string

    $len = strlen( $string );

if( $len > 40 ){

    echo 
    'this array contain a string wich length is greater than 40. Array key: 
    ' .$key. ' | array string: ' .$string;

    break;

 }

}

?>