Custom Implementation of array_flip Without Using PHP Array Functions
The array_flip function in PHP exchanges the keys and values of an array. Below is a custom implementation of this functionality without using PHP’s built-in array functions.
Code Example:
<?php
function custom_array_flip($array) {
$result = [];
// Loop through the array
foreach ($array as $key => $value) {
// Ensure the value can be used as a key
if (is_scalar($value)) {
$result[$value] = $key;
}
}
return $result;
}
// Example usage
$inputArray = ['a' => 1, 'b' => 2, 'c' => 3];
$flippedArray = custom_array_flip($inputArray);
print_r($flippedArray);
?>
Output:
Array
(
[1] => a
[2] => b
[3] => c
)
Explanation:
- Input Parameter:
- $array: The input array whose keys and values need to be swapped.
- Result Initialization:
- Create an empty $result array to store the flipped key-value pairs.
- Iteration:
- Use a foreach loop to iterate over the input array.
- For each key-value pair:
- Ensure the value is a scalar (string, integer, or float) because PHP keys must be scalar.
- Add the value as the key and the key as the value in the $result array.
- Output:
- Return the $result array with flipped keys and values.
Keep Learning 🙂