Today I re-examined the array_merge() function due to a bug.
Definition: array_merge — Merge one or more arrays
Specification: array array_merge(array $array1
[, array $...
])
Instructions:
1. Combine the cells of one or more arrays, and the values in one array are appended to the previous array behind.
2. If the input array has the same string key name, the value after the key name will overwrite the previous value. However, if the array contains numeric key names, the subsequent value will not overwrite the original value, but will be appended to it.
3. If only one array is given and the array is numerically indexed, the key names will be re-indexed in a continuous manner.
This function has detailed examples in the manual and is also very versatile and practical.
A problem I encountered today was a warning in the manual, but I didn't notice it before, which resulted in a fatal error. As follows:
PHP >= version 5.0, array_merge() only accepts parameters of type array. However, you can use casts to combine other types.
Pay attention to the array variables generated by foreach and other codes. Either initialize the variable to an empty array, or perform a forced conversion during merging. Otherwise, you will suffer a lot. Therefore, it is also a good idea to maintain a habit of initializing variables.
Merge arrays
1. If the two arrays have the same string key name:
$book1 = array(linux=>linux server configuration and management,php =>PHP Programming);
$book2 = array(linux=>Server Configuration and Management,jsp=>PHP);
$result = array_merge($book1,$book2);
print_r($result);
?>
The output is:
Array ( [linux] => Server Configuration and Management [php] => PHP Programming [jsp] => PHP )
Indicates that the latter will replace the former.
2. If the two arrays have the same numerical key name:
$book1 = array (linux server configuration and management, PHP programming);
$book2 = array(server configuration and management, PHP);
$result = array_merge($book1,$book2);
print_r($result);
?>
The result is:
Array ( [0] => linux server configuration and management [1] => PHP programming [2] => Server configuration and management [3] => PHP )
-- -I don’t know if it’s clear
You can use custom functions
function array_add($str1,$str2) {
if ( !is_array($str1) ) {
return;
}
if ( is_array($str2) ) {
$result = array_merge($str1,$str2);
} else {
$result = array_push($str1,$str2);
}
return $result;
}