1

So i need to return the number (6, 8 or 10) with the country value. So in the example, with 'sweden' its supposed to return 8 but the key of the array is apparently just Array(). Is the wrong in the structure of my array or the usage of array_keys?

$list= array (
  'list' => 
  array (
    6 => 
    array (
        'default',
        'finland'
    ),
    8 => 
    array (
        'sweden',
        'norway'
    ),
    10 => 
    array (
        'germany',
        'belgia'
    ),
  ),
);
print_r(array_keys($list, "sweden"));

return: Array()

4
  • Possible duplicate of PHP Multidimensional Array Searching (Find key by specific value) Commented Jan 1, 2019 at 1:26
  • doesnt look to be Commented Jan 1, 2019 at 1:28
  • What? use the accepted Answer that is working ;) arrray_keys isn't working with multidimensional arrays very well. Commented Jan 1, 2019 at 1:29
  • in that question its an associative array and is looking for 'slug' with slugs value, this is different Commented Jan 1, 2019 at 1:32

3 Answers 3

3

You have two problems.

First, the array you want to search is $list['list'], not $list itself.

Second, the second argument to array_keys() is only useful for 1-dimensional arrays. You have a 2-dimensional array, but array_keys() will not automatically search inside the nested arrays. So you need to write your own loop or use array_filter().

$results = array();
foreach ($list['list'] as $key => $value) {
    if (array_search('sweden', $value) !== false) {
        $results[] = $key;
    }
}
print_r($results);
Sign up to request clarification or add additional context in comments.

2 Comments

im getting a Parse error: syntax error, unexpected 'as' , do i need to edit something?
Should be foreach, not for
0

use foreach for it.

foreach ($list as $key => $value){

}

Comments

0

I think this is what you want

foreach($list as $key => $value ){  
        $arr = array_keys($value);//this has your (6, 8 or 10)         
        foreach($arr as $val){
             print_r($value[$val]);//showing array data of 6,8,10 indexes
        }  
    }

output: enter image description here

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.