0

How does one loop through an array and then subsequently check to see if the current selected element is a key? Thanks.

E.g. for the following:

for($i=0;$i<count($arr);$i++) {
  //if($arr[$i]) == key, or typeOf($arr[$i]) == key, then doSomething();
}
5
  • 1
    Do you mean that the element value equals key ? Commented Feb 28, 2012 at 10:29
  • what do you mean by "current selected element " and "is a key" Commented Feb 28, 2012 at 10:30
  • 1
    What do you mean by that? Every element in the array consists of a key and value. Do you mean the value is a key in another array? Commented Feb 28, 2012 at 10:30
  • edit the question instead of placing the example in a comment Commented Feb 28, 2012 at 10:31
  • key is not a datatype or anything in PHP (certainly not a keyword). It's still not clear what you want to do. What is key in your example? Commented Feb 28, 2012 at 10:32

1 Answer 1

2

If you want to check if a key exists in an array, then use array_key_exists()

//check if whatever is $key is a key in $array
if(array_key_exists( $key , $array )){
    //do something because it's a key
} else {
    //key not found. not a key
}

to do the other way around and get key if value exists, use array_search():

$array = array(
    0 => 'blue', 
    1 => 'red', 
    2 => 'green', 
    3 => 'red'
);

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I sincerely appreciate your answer! However, an additional trouble is acquiring the actual key itself (e.g. "and"=>"word" - how can I get the string of "and" by this means?). Thanks!
@user784446: IMO it would be much easier to help you, if you provide an example with the data you have (input) and the result you want to get.
I'm trying to loop through an array and test to see if either the key or the value to which it's associated passes a strstr test.
if you want to get the value, use a key. in PHP, you can also get the key using the value. updated my answer.
@user784446: Then use a foreach loop foreach($arr as $key => $value)... it seems to be the same problem than your previous question refers to.

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.