1

I have an array that is assigned to $elements. When I use array_keys to get the keys, I get what you would expect.

print_r(array_keys($elements));

Results in:

Array
(
    [0] => anchor-namecontentblock_areaBlock0contentblock11_1
    [1] => anchor-namecontentblock_areaBlock0contentblock22_1
    [2] => anchor-namecontentblock_areaBlock0contentblock33_1
...

But when I try to use array_keys with a search value, I get an empty array.

print_r(array_keys($elements, "anchor-namecontentblock_areaBlock0contentblock11_1"));

Should the result not be:

Array
(
    [0] => 0
)

Am I missing something?

6
  • Can we have the content of $elements? Commented Mar 25, 2015 at 21:43
  • 1
    Yep! You're definitely missing array_search() Commented Mar 25, 2015 at 21:43
  • 1
    @Rizier123 The array being printed out here is the result of array_keys($elements) not the original array. array_search() is to search for values, not keys. Commented Mar 25, 2015 at 21:44
  • Have XDebug set up too. Commented Mar 25, 2015 at 21:45
  • 1
    @D4V1D From the manual: Searches the array for a given value and returns the corresponding key if successful So OP wants to find the key from the value Commented Mar 25, 2015 at 21:47

2 Answers 2

4

You're doing the wrong array_keys search. Your anchor-name... values are KEYS in the original array, not VALUES. As such, your array_keys search argument is useless - it'll be searching the values of the original array, e.g.

$foo = array(
   'anchor-namecontentblock_areaBlock0contentblock11_1' => 'somevalue'
   etc..
                            searched by array_keys---------^^^^^^^^^^

You'd need do something more like:

$results = array_search('anchor-name...', array_keys($elements)));
           ^^^^^^^^^^^^^

instead.

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

1 Comment

Awesome. Thanks MB. Just to clarify though, array_search requires the string as the 1st parameter and the array as the 2nd: array_search('anchor-name...', array_keys($elements));
3

Specifying a search parameter to array_keys allows you to retrieve the key(s) corresponding to one or more values in your array. You're passing it one of your array keys, so the function is returning no results.

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.