Catfish Posted June 18, 2010 Share Posted June 18, 2010 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? Link to comment https://forums.phpfreaks.com/topic/205128-compare-an-array-contents-and-create-a-new-array/ Share on other sites More sharing options...
kenrbnsn Posted June 18, 2010 Share Posted June 18, 2010 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 Link to comment https://forums.phpfreaks.com/topic/205128-compare-an-array-contents-and-create-a-new-array/#findComment-1073739 Share on other sites More sharing options...
Catfish Posted June 18, 2010 Author Share Posted June 18, 2010 Thanks Ken! Your code worked a treat. I didn't know how to describe what I wanted to do and summarize it in some keywords so I could look for it online. I still don't really! Link to comment https://forums.phpfreaks.com/topic/205128-compare-an-array-contents-and-create-a-new-array/#findComment-1073772 Share on other sites More sharing options...
kenrbnsn Posted June 18, 2010 Share Posted June 18, 2010 The best reference on PHP arrays that I know of is the PHP Manual. Just go there when you are looking for anything to do with arrays. Ken Link to comment https://forums.phpfreaks.com/topic/205128-compare-an-array-contents-and-create-a-new-array/#findComment-1073774 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.