1

Is there a way to select an array element by its key, without having to iterate through the set array_keys($arr) - ?

Thanks!

2 Answers 2

8

If you want to select an element by it's key all you do is this:

<?php
echo $array_name['KEY_NAME'];
?>

Where "KEY_NAME" is the key you have given to that element in the array.

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

3 Comments

Apologies, it must be the value I'm testing for (albeit it seems that this just simply selects the value to which the key associates and not the value of the key itself). E.g. I'd like to do the following... $arr = array("value", "a"=>"b"); if($arr["value"]) { //output something } else { //output something converse }
Here 'value' is the actual value of the array if you wanted to access it you would do $arr[0] has you have not given it a key name like you did you b.
Thanks. Accepting the associated value if testing the key value succeeds doesn't seem to work for some reason. Ordinarily, I'd be required to test the value from the set returned by array_keys($arr) but would prefer an alternative that doesn't entail storing a second copy of an entire set.
1

Apologies for mis-presenting this problem but have found a long-lost solution now! Simply use array_key_exists($key, $array) to test for $key in $array.

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.