Return Values from a Single Column in an Input Array Without Using PHP Functions
Here’s how you can manually extract values from a single column in a multi-dimensional array without using PHP’s array_column function.
Code Example:
<!DOCTYPE html>
<html>
<body>
<?php
function getColumnValues($array, $columnKey) {
$columnValues = [];
foreach ($array as $row) {
// Check if the specified key exists in the current row
if (isset($row[$columnKey])) {
$columnValues[] = $row[$columnKey];
}
}
return $columnValues;
}
// Example Usage
$data = [
["id" => 1, "name" => "Mayank Singh", "age" => 25],
["id" => 2, "name" => "Amit Kumar", "age" => 30],
["id" => 3, "name" => "Dharmender Singh", "age" => 35]
];
$columnKey = "name";
$result = getColumnValues($data, $columnKey);
print_r($result);
?>
</body>
</html>
Output:
Array
(
[0] => Mayank Singh
[1] => Amit Kumar
[2] => Dharmender Singh
)
Explanation
- Initialize an Empty Array:
- $columnValues: This array will store the extracted column values.
- Iterate Through the Input Array:
- Loop through each row of the array.
- Check for Key Existence:
- Use isset($row[$columnKey]) to ensure the specified column exists in the current row.
- Extract and Append:
- If the key exists, add its value to the $columnValues array.
- Return the Result:
- After the loop, return the $columnValues array.
Keep Learning 🙂
This manual implementation of extracting column values avoids using any built-in PHP functions while ensuring clarity and efficiency.