Home  >  Article  >  Backend Development  >  Let’s talk about how to create and manipulate two-dimensional arrays in PHP

Let’s talk about how to create and manipulate two-dimensional arrays in PHP

PHPz
PHPzOriginal
2023-04-12 09:20:52550browse

Creating a two-dimensional array in PHP is very simple, just add an array within an array. The following is an example array:

$myArray = array (
    array("David", 28, "Male"),
    array("Sarah", 23, "Female"),
    array("John", 34, "Male")
);

This array contains three arrays, each array contains three elements. The first element is name, the second is age, and the third is gender.

If you want to add a new array, just add a new array in the array:

$myArray[] = array("Emily", 29, "Female");

The above statement will be added in $myArray A new array named "Emily". The array now contains four arrays.

If you want to access the elements in the two-dimensional array, you can use the following syntax:

echo $myArray[0][0]; // 输出 "David"
echo $myArray[1][1]; // 输出 "23"
echo $myArray[2][2]; // 输出 "Male"
echo $myArray[3][0]; // 输出 "Emily"

You can add more arrays in the two-dimensional array as needed and use the above syntax Access elements in an array.

Alternatively, you can use a loop to iterate through all elements in a two-dimensional array. Here is an example:

foreach($myArray as $row) {
    foreach($row as $value) {
        echo $value . " ";
    }
    echo "<br>";
}

The above code will iterate through all the elements in the $myArray array and print them to the page.

Hope the above content can help you understand how to create and operate two-dimensional arrays in PHP.

The above is the detailed content of Let’s talk about how to create and manipulate two-dimensional arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn