How can a callback function be utilized to manipulate values in an array in PHP?
To manipulate values in an array using a callback function in PHP, you can use the array_map() function. This function applies a callback function to each element in the array and returns a new array with the modified values. The callback function can perform any desired manipulation on the array values.
// Original array
$numbers = [1, 2, 3, 4, 5];
// Callback function to multiply each element by 2
function multiplyByTwo($num) {
return $num * 2;
}
// Apply the callback function to each element in the array
$modifiedNumbers = array_map('multiplyByTwo', $numbers);
// Output the modified array
print_r($modifiedNumbers);
Related questions
-
PHP form submissions variables
-
FPDF PHP dynamic positioning
-
HTTP POST request API response handling error handling