Home > Backend Development > PHP Problem > 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
Release: 2023-04-12 10:27:13
Original
597 people have browsed it

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")
);
Copy after login

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");
Copy after login

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"
Copy after login

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>";
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template