tgifred
tgifred

Reputation: 109

use values of first array to select values of second array

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 )

Upvotes: 1

Views: 113

Answers (2)

Rizier123
Rizier123

Reputation: 59701

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 )

Upvotes: 1

Federico Moretti
Federico Moretti

Reputation: 126

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);
?>

Upvotes: 1

Related Questions