1

I have the following array (array below) and I am trying to get the key of the value of the sub-array.

$array = array(
  'USD' => array (
      0 => 1.79,
      1 => 3.58,
      2 => 5.37,
      3 => 7.16,
      4 => 8.95,
    ),
  'CAD' =>  array (
      0 => 2.49,
      1 => 4.98,
      2 => 7.47,
      3 => 9.96,
      4 => 12.45,
    ),
  'EUR' =>  array (
      0 => 1.99,
      1 => 3.98,
      2 => 5.97,
      3 => 7.96,
      4 => 9.95,
    )
);  
$item_to_get = array_search(5.97, $array);

CURRENT OUTPUT

false

EXPECTED OUTPUT => the parent key name

EUR
5
  • I think array_search works only on one dimensional array...btw what happen if multiple value are the same?? Commented Nov 28, 2015 at 15:15
  • The result is exactly as expected considering the documentation of the function: it searches through the values inside the array, not throught the elements of the arrays values. Commented Nov 28, 2015 at 15:15
  • And in order to achieve expected output, i ran out of ideas. Commented Nov 28, 2015 at 15:16
  • 1
    Duplicate of: stackoverflow.com/questions/28472779/recursive-array-search Commented Nov 28, 2015 at 15:18
  • @arkascha Worked fine with a bit of adapting sandbox.onlinephpfunctions.com/code/… Commented Nov 28, 2015 at 15:33

2 Answers 2

2

array_search function is not recursive, so you have to iterate over the array and search in the subarrays:

$foundInParent = false;
foreach($array as $parentKey => $subArray) {
  if (array_search(5.97, $subArray)) {
    $foundInParent = $parentKey;
    break;
  }
}

echo $foundInParent;

Just wrap it in a function..

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

4 Comments

@Adrian you need to RETURN the value ;) sandbox.onlinephpfunctions.com/code/…
Ah Yes, wasn't attentive.
@Adrian just a tip, when you create a function first define the return value and put the return statement at the end.. and then start writing your logic in between..
0

This is not the way array_search() is supposed to work - see here: http://php.net/manual/en/function.array-search.php

You probably need array_walk() with a custom callback function. Or use foreach() to iterate over the outer array, then array_search() inside the foreach-loop.

I any case, I recommend setting up the array differently in the first place!

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.