0

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;
}
1
  • 1
    use a loop and move on to the next problem! Commented Sep 2, 2014 at 14:04

3 Answers 3

4
$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);
Sign up to request clarification or add additional context in comments.

3 Comments

Are there any reason to use this one instead of array_search ? Smaller complexity maybe ?
Simpler because you don't need to loop, just uses two built-in functions, no need for an if test, so probably also micro-scopically faster too
Yeah, I noticed about the if check at the same time I asked you. :)
0

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 )

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.