Master PHP Functions: Defining, Passing, Looping, and Returning Arrays
Learn how to define, pass, loop through, and return arrays within PHP functions, with clear examples of using array(), for and foreach loops, and return statements to build efficient and robust backend code.
In PHP programming, arrays are a fundamental data type that store multiple values as key‑value pairs, and they are frequently used when writing custom functions.
1. Defining an array
In PHP you can define an array with the array() function. For example:
$my_array = array(1, 2, 3);You can also define an array inside a function:
function my_function() {
$my_array = array(1, 2, 3);
}2. Passing an array as a parameter
To operate on an array inside a function, pass it as an argument:
function my_function($my_array) {
// operate on $my_array
}This example defines my_function and passes $my_array to it.
3. Traversing an array
PHP provides two common ways to iterate over an array.
Using a for loop:
function my_function($my_array) {
for ($i = 0; $i < count($my_array); $i++) {
echo $my_array[$i] . "<br>";
}
}Using a foreach loop:
function my_function($my_array) {
foreach ($my_array as $value) {
echo $value . "<br>";
}
}4. Returning an array
After modifying an array, return it with the return statement:
return $my_array;5. Full example
The following code demonstrates defining, passing, iterating, modifying, and returning an array within a PHP function:
function my_function($my_array) {
for ($i = 0; $i < count($my_array); $i++) {
$my_array[$i] = $my_array[$i] * $my_array[$i];
}
return $my_array;
}
$my_input_array = array(1, 2, 3);
$my_output_array = my_function($my_input_array);
foreach ($my_output_array as $value) {
echo $value . "<br>";
}Summary
Defining, passing, iterating, and returning arrays in PHP functions are common operations; choosing the appropriate loop (for or foreach) and correctly handling the array ensures efficient and reliable PHP applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
