Can we pass an array as parameter in any function in PHP?
Yes, you can pass an array as a parameter to a function in PHP. To do this, you will need to specify the type of the parameter as an array by adding the array
keyword before the parameter name in the function definition.
For example:
<?php
function foo(array $arr)
{
$sum = array_sum($arr); // calculate the sum of the array
return "The sum of the array is: $sum";
}
// Example usage:
$array = [1, 2, 3, 4, 5];
echo foo($array); // outputs "The sum of the array is: 15"
You can then call the function and pass it an array as an argument, like this:
<?php
$myArray = [1, 2, 3];
function foo(array $arr)
{
$sum = array_sum($arr); // calculate the sum of the array
echo "The sum of the array is: $sum";
}
foo($myArray);
Inside the function, you can access the elements of the array using standard array notation. For example, you could use a foreach loop to iterate over the array like this:
<?php
function processArray(array $arr)
{
foreach ($arr as $element) {
echo $element . "!";
}
}
// Example usage:
$array = ["apple", "banana", "orange"];
processArray($array); // outputs "apple!banana!orange!"