简体   繁体   English

如何在数组中搜索整数和strlen

[英]How to search in an Array for integer and strlen

I would like to search in an Array if there is a key that has a stringlength of exactly 5 characters and further on it must be of type integer. 我想在一个数组中搜索是否有一个字符串,它的字符串长度正好是5个字符,并且进一步它必须是整数类型。

I tried: 我试过了:

$key = array_search( strlen( is_int($array)=== true) === 5 , $array); 

but this does not work. 但这不起作用。 So I would like to know if it exists and which key it is. 所以我想知道它是否存在以及它是哪个键。

Thanks alot. 非常感谢。

How about: 怎么样:

$filtered = array_filter($array, function($v){
  return !!(is_int($v)&&strlen($v)==5);
});

run code 运行代码

Essentially array_filter iterates over each element of the array passing each value $v to a callable function. 本质上, array_filter遍历数组的每个元素,并将每个值$v传递给可调用函数。 Depending on your desired conditions it returns a boolean (true or false) as to whether it is kept in the resultant $filtered array. 根据您所需的条件,它返回一个布尔值(true或false),是否将其保留在结果$filtered数组中。

the !! !! is not strictly necessary as (...) will ensure boolean is cast correctly but the exclamation marks are just syntactic sugar - personal preference for readability. 并不是绝对必要的,因为(...)将确保布尔值正确地转换,但是感叹号只是语法糖-个人对可读性的偏爱。

That's not how array_search() works. 那不是array_search()的工作方式。 It searches the value for a matching string, and returns a key. 它在值中搜索匹配的字符串,然后返回键。 If you want to search a key, your best bet is to simply iterate over it. 如果要搜索键,最好的选择就是简单地对其进行迭代。

foreach ($array as $key => $value) {
    if (strlen($key) === 5) { 
        echo $key . ": " . $value; 
        break; //Finish the loop once a match is found
    }
}

array_search will not work like this try array_search将无法像这样尝试

foreach ($array as $key => $value) {

if ((strlen($value) == 5) && is_int($value)) 
 { 
    echo $key . ": " . $value;  
 }
}

You can use array_walk 您可以使用array_walk

array_walk($array, function(&$value, $index){
if (strlen($value) == 5 && (is_int($index))) echo "$index:$value";
});

array walk iterates through each element and applies the user defined function 数组遍历遍历每个元素并应用用户定义的函数

here is sample example to compare value with integer and exact 5 character 这是将值与整数和精确的5个字符进行比较的示例示例

$array = array(12345,'asatae');

$key_val = array();
foreach($array as $each_val){    
    if(is_int($each_val) && strlen($each_val) == 5){        
        $key_val[] = $each_val;
    }
}

echo "<pre>";
print_r($key_val);

you output will be like 您的输出将像

Array
(
    [0] => 12345
)

Notice : in array must be integer value not quotes 注意:数组中的值必须为整数,不能用引号引起来

like array(23, "23", 23.5, "23.5") 像array(23,“ 23”,23.5,“ 23.5”)

23 is integer with first key.. 23是带有第一个键的整数。

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

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