1

I want to use the values of my first array $selection (which are always numbers) as the keys for the other array $categories and output only the selected keys.

See code below, very new to php.

<?php

    $selection = array('1', '4', '5');
    $categories = array('fruit', 'bread', 'desert', 'soup', 'pizza');

    $multiple = array_combine($selection, $categories);

    print_r($multiple);

?>

so it should output something like:

Array ( [1] => fruit [4] => soup [5] => pizza )
3
  • How do you want to handle cases where the length of $selection and $categories differ? Commented May 1, 2015 at 20:17
  • exactly. This example here only works when the number of values are the same. I need a solution to just select the values of the second array with the given values of the first. Commented May 1, 2015 at 20:19
  • So where are we with this question? Commented May 1, 2015 at 20:40

2 Answers 2

1

Something like this works for you?

<?php
    $selection = array('1', '4', '5');
    $categories = array('fruit', 'bread', 'desert', 'soup', 'pizza');
    $multiple = array();

    foreach($selection as $value) {
        if (isset($categories[$value - 1])) 
            $multiple[$value] = $categories[$value - 1];
        }
    }

    print_r($multiple);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

How does this in any way solve his problem? isset($categories[$value] will always be false.
I don't think so, why would it be?
yes it does, much simpler this way cause it doesn't matter for me where the counting starts. Thanks Federico and Rizier123!
1

This should work for you:

Just get the array_intersect_key() from both arrays: $selection and $categories.

Note that since an array is index based 0 you have to go through your $selection array with array_map() and subtract one from each value to then use array_flip().

And at the end you can simply array_combine() the intersect of both arrays with the $selection array.

$result = array_combine($selection,
    array_intersect_key(
        $categories,
        array_flip(
            array_map(function($v){
                return $v-1;
            }, $selection)
        )
    ));

output:

Array ( [1] => fruit [4] => soup [5] => pizza )

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.