简体   繁体   中英

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.

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. Depending on your desired conditions it returns a boolean (true or false) as to whether it is kept in the resultant $filtered array.

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. 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

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

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

You can use 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

$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")

23 is integer with first key..

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.

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