DavSev DavSev - 26 days ago 13
PHP Question

php array comperation, complete missing array locations

I have two arrays:

$array1 = array('name', 'email', 'phone');
$array2 = array('name' => 'John', 'phone' => '55-555-555');


I have created a HTML table from this two arrays, array1 is the table heads, and array2 is the td contents.

what happens now is that becouse array2 is missing a value (email in this case) I will get the phone data under the mail column.
i would like to get this result:

$array2 = array('name' => 'John', 'email' => ' ', 'phone' => '55-555-555');


I tried to follow this answer, but it has two main problems:


  1. the array keys desapear.

  2. the
    0
    values are added at the end of the array and not in their original location.


Answer

Your source array is wrong. You need to have something like this:

$array1 = array('name' => '', 'email' => '', 'phone' => '');

And if you want to extend with the empty values, you can use:

$array2 = array('name' => 'John', 'phone' => '55-555-555');

The final array can be made by using array_merge:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

$array2 = array_merge($array1, $array2);

You will get this as output:

array('name' => 'John', 'email' => '', 'phone' => '55-555-555');

Full Code

$array1 = array('name' => '', 'email' => '', 'phone' => '');
$array2 = array('name' => 'John', 'phone' => '55-555-555');
$array2 = array_merge($array1, $array2);
var_export($array2);

Output

array (
  'name' => 'John',
  'email' => '',
  'phone' => '55-555-555',
)

Demo: http://ideone.com/7zlab7


Better Explanation

// Have a base array that has all the required fields.
$baseArr = array('name', 'email', 'phone', 'password');
// Get your array with the initial values, (without a few fields).
$myArray = array('name' => 'david', 'email' => 'aaa@aaa.aaa', 'phone'=> '123456789');
// Now make a new array on the fly with array_fill_keys using the baseArr
// and merge with the original user array.
$myArray = array_merge(array_fill_keys($baseArr, ''), $myArray);
// The resultant array will have all the fields.
print_r($myArray);

Output

Array
(
    [name] => david
    [email] => aaa@aaa.aaa
    [phone] => 123456789
    [password] => 
)

Demo: http://ideone.com/XLCMN9