0

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.

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's cool, how does it work? Consider explaining things if they aren't obvious (the OP is a beginner, so it isn't obvious). Adding comments to the code is a great way.
@MadaraUchiha fair enough, will do
1

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

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.