Q. Can you provide an explanation of array_map() function in PHP along with an illustrative example?
Asnwer:
The array_map() function in PHP is used to apply a callback function to each element of one or more arrays. It takes one or more arrays as input and applies the specified callback function to each corresponding element of the arrays. The result is a new array containing the modified elements.
Here's the basic syntax of array_map():
array_map(callback, array1, array2, ...);
callback: The callback function to apply to each element.
array1, array2, ...: The arrays to process.
Now, let's look at an illustrative example to understand how array_map() works:
<?php
// Define a callback function
function square($num) {
return $num * $num;
}
// An array of numbers
$numbers = [1, 2, 3, 4, 5];
// Use array_map() to apply the square function to each element in $numbers
$squaredNumbers = array_map('square', $numbers);
// Display the original and modified arrays
print_r($numbers);
print_r($squaredNumbers);
?>
In this example:
We define a callback function named square that takes a number and returns its square.
We have an array of numbers called $numbers.
We use array_map() to apply the square function to each element in the $numbers array, resulting in a new array $squaredNumbers.
We then use print_r() to display both the original $numbers array and the modified $squaredNumbers array.
The output will be:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
As you can see, array_map() applied the square function to each element in the $numbers array, resulting in a new array with the squared values.
js
Thursday, December 7, 2023
Can you provide an explanation of array_map() function in PHP along with an illustrative example?
Subscribe to:
Post Comments (Atom)
CBSE Class VII English (Poorvi) Unit 5: Bravehearts — Rani Abbakka Questions and Answers
Let us do these activities before we read I. Solve the riddle given below and share your answer with your classmates and the...
-
Total No. of printed pages: 7 DLIEC/23/2024 District Level Internal Examination Committee, Kamrup Half Yearly Examination, 2023-24 Class:...
-
To check whether Apache is installed on an Ubuntu system, you can use the following methods: 1. Check Apache Service Status Run the f...
-
CBSE Class VIII Mathematics (Ganita Prakash) — 160-Day Lesson Plan A comprehensive, day-to-day instructional p...
No comments:
Post a Comment