php array comperation, complete missing array locations -
i have 2 arrays:
$array1 = array('name', 'email', 'phone'); $array2 = array('name' => 'john', 'phone' => '55-555-555');
i have created html table 2 arrays, array1 table heads, , array2 td contents.
what happens becouse array2 missing value (email in case) phone data under mail column. result:
$array2 = array('name' => 'john', 'email' => ' ', 'phone' => '55-555-555');
i tried follow this answer, has 2 main problems:
- the array keys desapear.
- the
0
values added @ end of array , not in original location.
your source array wrong. need have this:
$array1 = array('name' => '', 'email' => '', 'phone' => '');
and if want extend empty values, can use:
$array2 = array('name' => 'john', 'phone' => '55-555-555');
the final array can made using array_merge
:
merges elements of 1 or more arrays values of 1 appended end of previous one. returns resulting array.
$array2 = array_merge($array1, $array2);
you 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 base array has required fields. $basearr = array('name', 'email', 'phone', 'password'); // array initial values, (without few fields). $myarray = array('name' => 'david', 'email' => 'aaa@aaa.aaa', 'phone'=> '123456789'); // make new array on fly array_fill_keys using basearr // , merge original user array. $myarray = array_merge(array_fill_keys($basearr, ''), $myarray); // resultant array have fields. print_r($myarray);
output
array ( [name] => david [email] => aaa@aaa.aaa [phone] => 123456789 [password] => )
demo: http://ideone.com/xlcmn9
Comments
Post a Comment