Re-understanding PHP Array_merge functions
The next Array_merge () function was re-examined today for a bug.
Definition: array_merge-merge one or more arrays
Spec: Array array_merge (array $array 1 [, Array $ ...])
Description
1. Merge one or more arrays of cells, and the values in one array are appended to the previous array.
2. If the input array has the same string key name, the value following the key name overrides the previous value. However, if the array contains a numeric key name, the subsequent value will not overwrite the original value, but append to the back.
3. If only one array is given and the array is a numeric index, the key name is sequentially indexed.
This function is an exhaustive example in the manual and is useful in a wide range of applications.
One of the problems I encountered today was a warning in the manual, but not previously noticed, leading to a fatal error. As follows:
PHP >= version 5.0, Array_merge () accepts only parameters of array type. However, you can use casts to merge other types.
Be aware of the array variables that are generated by the foreach code, either initialize the variable to an empty array, or make a cast when merging. Otherwise, there will be great pain to eat. So it's good to keep a habit of initializing variables.
Merging arrays into two different situations in PHP
1, if the two arrays have the same string key name:
<?php
$book 1 = array (' Linux ' => ' Linux server Configuration and Management ', ' php ' => ' PHP programming ');
$book 2 = Array (' Linux ' => ' Server configuration and Management ', ' JSP ' => ' PHP ');
$result = Array_merge ($book 1, $book 2);
Print_r ($result);
? >
The output is:
Array ([Linux] => server configuration and Management [PHP] => php design [jsp] => PHP)
Description, the latter replaces the former. However, if you are using array_merge_recursive (), you can keep it and make a child array. Such as:
<?php
$book 1 = array (' Linux ' => ' Linux server Configuration and Management ', ' php ' => ' PHP programming ');
$book 2 = Array (' Linux ' => ' Server configuration and Management ', ' JSP ' => ' PHP ');
$result = array_merge_recursive ($book 1, $book 2);
Print_r ($result);
? >
The output is:
Array ([Linux] => Array ([0] => Linux server configuration and management [1] => server configuration and Management) [PHP] => PHP programming [JSP] => PHP)
2, if the two arrays have the same numeric key name:
<?php
$book 1 = array (' Linux server Configuration and Management ', ' PHP programming ');
$book 2 = Array (' Server configuration and Management ', ' PHP ');
$result = Array_merge ($book 1, $book 2);
Print_r ($result);
? >
The result:
Array ([0] => Linux server configuration and management [1] => PHP design [2] => server configuration and management [3] => PHP)
At this point, if the array contains the same numeric key name, then the preceding value will not be overwritten, but the following key values are incremented sequentially, attached. You see, ^_^.