Master PHP Functions: Define, Pass, Loop, and Return Arrays

This guide explains how to define, pass, iterate over, and return arrays within PHP functions, covering array creation with array(), parameter passing, traversal using both for and foreach loops, and returning modified arrays, complete with full code examples for each step.

php Courses
php Courses
php Courses
Master PHP Functions: Define, Pass, Loop, and Return Arrays

In PHP programming, arrays are a common and essential data type that can store multiple values as key‑value pairs, and they are frequently used inside custom functions.

1. Define an array

Use the array() function to create an array. Example: $my_array = array(1, 2, 3); Inside a function you can define an array in the same way:

function my_function() {
    $my_array = array(1, 2, 3);
}

2. Pass array as a parameter

When a function needs to operate on an array, pass the array as an argument:

function my_function($my_array) {
    // operate on $my_array
}

Call the function with an array variable.

3. Iterate over an array

Two common ways to traverse an array are a for loop and a foreach loop.

function my_function($my_array) {
    for ($i = 0; $i < count($my_array); $i++) {
        echo $my_array[$i] . "<br>";
    }
}
function my_function($my_array) {
    foreach ($my_array as $value) {
        echo $value . "<br>";
    }
}

4. Return an array

After processing, return the modified array to the caller:

return $my_array;

5. Full example

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 very common operations; choosing the appropriate loop (for or foreach) and correctly handling the array ensures efficient, reliable PHP applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPfunctionsArraysforeachfor loopCode Tutorial
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.