Combine Two Arrays Without Using PHP’s Built-In Function
To manually combine two arrays into an associative array, where one array serves as the keys and the other as the values, you can use the following approach:
Code Example
<!DOCTYPE html>
<html>
<body>
<?php
function combineArrays($keys, $values) {
$combinedArray = [];
$minLength = count($keys) < count($values) ? count($keys) : count($values); // Find the shorter array
for ($i = 0; $i < $minLength; $i++) {
$combinedArray[$keys[$i]] = $values[$i];
}
return $combinedArray;
}
// Example Usage
$keys = ["name", "age", "city"];
$values = ["Dharmender Singh", 25, "Bangalore"];
$result = combineArrays($keys, $values);
print_r($result);
?>
</body>
</html>
Output:
Array
(
[name] => Dharmender Singh
[age] => 25
[city] => Bangalore
)
Explanation
- Initialize an Empty Array:
- $combinedArray is used to store the resulting associative array.
- Determine the Shorter Array Length:
- To avoid errors, the loop runs up to the length of the shorter array ($keys or $values).
- Loop Through Arrays:
- Use a for loop to iterate through both arrays simultaneously.
- Assign the value from $values to the corresponding key from $keys.
- Return the Combined Array:
- After the loop, return the resulting associative array.
Notes
- If the $keys array is longer than the $values array, extra keys will not be included.
- If the $values array is longer than the $keys array, extra values will be ignored.
This manual approach mimics the behavior of PHP’s array_combine function.
Keep Learning 🙂