Get array values ​​based on second key of an array in PHP

Let's take two arrays:

$aliases = array(
    'id'   => 'real_id',
    'date' => 'real_date',
    'name' => 'real_name'
);
$data = array(
    'id'   => 1,
    'name' => 'Lorem ipsum'
);

      

I would like to get each value $aliases

for the keys defined in the array $data

(no need to check if the key exists, I already did it at this point using array_intersect_key()

). Here's the expected output:

array('real_id', 'real_name');

      

Currently I can do it with foreach

:

$realkeys = array();
foreach(array_keys($data) as $key) {
    $realkeys[] = $aliases[$key];
}

      

But is there any PHP built-in function to do this more intelligently?

+3


source to share


1 answer


You can use PHP array_intersect_key

like this:

    <?php
        $aliases = array(
                'id'   => 'real_id',
                'date' => 'real_date',
                'name' => 'real_name'
        );
        $data = array(
                'id'   => 1,
                'name' => 'Lorem ipsum'
        );

        print_r(array_values(array_intersect_key($aliases, $data)));
    ?>

      



Array ([0] => real_id [1] => real_name)

+4


source







All Articles