How to Pass an Array into a Function in PHP ?
Last Updated :
02 Jan, 2024
This article will show you how to pass an array to function in PHP. When working with arrays, it is essential to understand how to pass them into functions for effective code organization and re-usability. This article explores various approaches to pass arrays into PHP functions, covering different methods and scenarios.
Approach 1: Passing by Value
A copy of the array is made when an array is passed to a function by value, and modifications inside the function do not affect the original array.
PHP
<?php
function arrayByValue( $arr ) {
$arr [0] = 100;
return $arr ;
}
$arr = [1, 2, 3];
$newArr = arrayByValue( $arr );
print_r( $newArr );
?>
|
Output
Array
(
[0] => 100
[1] => 2
[2] => 3
)
Approach 2: Passing by Reference
Passing an array by reference allows the function to modify the original array directly.
PHP
<?php
function arrayByReference(& $arr ) {
$arr [0] = 100;
}
$arr = [1, 2, 3];
arrayByReference( $arr );
print_r( $arr );
?>
|
Output
Array
(
[0] => 100
[1] => 2
[2] => 3
)
Approach 3: Using the func_get_args() Function
If the number of parameters is variable, the func_get_args() function can be used to access all parameters as an array.
PHP
<?php
function processArr() {
$args = func_get_args();
print_r( $args );
}
processArr(1, 'hello' , [3, 4]);
?>
|
Output
Array
(
[0] => 1
[1] => hello
[2] => Array
(
[0] => 3
[1] => 4
)
)
Share your thoughts in the comments
Please Login to comment...