Jump to content

Compare an array contents and create a new array


Catfish

Recommended Posts

Hi there,

 

I want to know how I would be able to compare an array filled with data against another array that holds the key names that are expected to be in the first array.

 

The first array may contain more or less data than is expected but the end result must be the data array with the key names from the second array.

 

Example:

 

$array1 = array ('key1' => 'value1', 'key2' => 'value2', 'key4' => 'value4', 'key5' => 'value5');

$array2 = array('key1', 'key2', 'key3');

 

I want to use the values in $array2 to say, "these are the field names that must be in the resulting array. nothing more and nothing less."

 

therefore, I need to know the code to turn $array1 into this:

 

$array1 = array ('key1 => 'value1', $key2 => 'value2', $key3 => '');

 

Note that the value of 'key3' will be empty because the original $array1 did not have a key3 key name or value.

 

Is there an existing function that does this? What would I google for to get the best results for a function like this?

I don't think there is a built-in function for this, but it's not hard to write on:

<?php
function xyz($ary,$keyary) {
    $new = array();
    foreach ($keyary as $key) {
       $new[$key] = (array_key_exists($key,$ary))?$ary[$key]:'';
    }
    return $new;
}
$array1 = array ('key1' => 'value1', 'key2' => 'value2', 'key4' => 'value4', 'key5' => 'value5');
$array2 = array('key1', 'key2', 'key3');
$array1 = xyz($array1,$array2);
echo '<pre>' . print_r($array1,true) . '</pre>';
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.