array_combine
and array_merge
are both PHP functions used for working with arrays, but they serve different purposes and have distinct behaviors:
array_combine:
Syntax:
array_combine(array $keys, array $values): array|false
Purpose: Combines two arrays into a single associative array, using one array for keys and another for values.
Example:
php$keys = ['name', 'age', 'country']; $values = ['John', 30, 'USA']; $combinedArray = array_combine($keys, $values); // Result: ['name' => 'John', 'age' => 30, 'country' => 'USA']
Notes:
- The number of elements in both arrays should be equal.
- If the arrays have different lengths,
array_combine
returnsfalse
.
array_merge:
Syntax:
array_merge(array ...$arrays): array
Purpose: Merges multiple arrays into a single array, preserving numeric keys and overwriting values with the same key from later arrays.
Example:
php$array1 = ['a' => 'apple', 'b' => 'banana']; $array2 = ['b' => 'blueberry', 'c' => 'cherry']; $mergedArray = array_merge($array1, $array2); // Result: ['a' => 'apple', 'b' => 'blueberry', 'c' => 'cherry']
Notes:
- Keys are preserved unless they are numeric and consecutive, in which case they are reindexed starting from zero.
- Values with the same key in later arrays overwrite earlier ones.
In summary:
array_combine
is used to create an associative array from two arrays, using one array for keys and another for values.array_merge
is used to merge multiple arrays into a single array, combining their elements while preserving or reindexing keys as necessary.
No comments:
Post a Comment