user1642018
user1642018

Reputation:

How to search multiple keys from predefined array?

i have predefined array of categories like this in key => value pair

$all_categories = array (
                    1 => 'friends',
                    2 => 'family',
                    3 => 'personal',
                    4 => 'public'
);

and i have new small array like this which are only values.

$searched_categories = array('family','public');

Now how can i get the keys from $all_categories array having values as $searched_categories ?

i want output like this

$output_array = array(2,4);

i can get single key using array_search but is there a prebuilt function for this ? or i have to create a loop to array_search all the values i have ?


is this proper way of achieving this ?

$output_array = array ();
foreach ($searched_categories as $value){
    $key = array_search($value, $all_categories );
    $output_array  = $key;
}

Upvotes: 0

Views: 91

Answers (3)

Clément Malet
Clément Malet

Reputation: 5090

array_search is doing the job, but you erase your array all the time and add $key regardless of the fact it could be equal to false from array_search :

foreach ($searched_categories as $value){
  $key = array_search($value, $all_categories );
  if ($key !== false) 
    $output_array[] = $key;
}

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212422

$all_categories = array (1 => 'friends', 2 => 'family', 3 => 'personal', 4 => 'public');

$searched_categories = array('family','public');

$output_array = array_keys(
    array_intersect(
        $all_categories,
        $searched_categories
    )
);
var_dump($output_array);

Upvotes: 4

Dan
Dan

Reputation: 9468

You could use a foreach loop and in_array.

foreach($all_categories as $key => $category){ //loop through your categories array
    if(in_array($category, $searched_categories)){ //check if category is in searched_catgories
        $output_array[] = $key; //if category is there, then save the key to your new array
    }
}

print_r($output_array); will give you Array ( [0] => 2 [1] => 4 )

Upvotes: 0

Related Questions