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.
Tags
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:
Example of passing an array as parameter in an function in PHP
<?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:
Example of passing an array as parameter in any function in PHP
<?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:
Example of foreach loop to iterate over an array in PHP
<?php
function processArray(array $arr)
{
foreach ($arr as $element) {
echo $element . "!";
}
}
// Example usage:
$array = ["apple", "banana", "orange"];
processArray($array); // outputs "apple!banana!orange!"