What is the difference between array_map and array_walk in PHP?
The main difference between `array_map` and `array_walk` in PHP is that `array_map` returns a new array with the elements modified by a callback function, while `array_walk` modifies the original array by reference. If you need to create a new array with modified elements, use `array_map`. If you want to modify the original array directly, use `array_walk`.
// Example using array_map to create a new array with modified elements
$numbers = [1, 2, 3, 4, 5];
$modifiedNumbers = array_map(function($num) {
return $num * 2;
}, $numbers);
print_r($modifiedNumbers);
// Example using array_walk to modify the original array
$numbers = [1, 2, 3, 4, 5];
array_walk($numbers, function(&$num) {
$num *= 2;
});
print_r($numbers);
Keywords
Related Questions
- What steps can be taken to troubleshoot and fix syntax highlighting issues in a PHP forum or code editor?
- What are the best practices for passing values to scripts in PHP when clicking on links?
- What is the potential security risk associated with using $_SERVER['PHP_SELF'] in a form action attribute in PHP?