How to get the value of a two-dimensional array in php

PHPz
Release: 2023-04-27 09:34:31
Original
809 people have browsed it

In PHP, a two-dimensional array is an array containing one or more arrays, where each sub-array has its own key and value. To get the values of a 2D array, you have to choose between an outer loop that iterates over each subarray, and an inner loop that iterates over the keys and values in each subarray.

The following are several ways to obtain the value of a two-dimensional array:

  1. foreach loop

You can use a foreach loop to obtain the value of a two-dimensional array. You can use a foreach statement in an outer loop to iterate through each sub-array in the main array. And inside the inner loop, you can use another foreach loop to iterate over the keys and values in each sub-array.

Sample code:

"; } ?>
Copy after login

Result:

Maths: 85 English: 82 Science: 90
Copy after login
Copy after login
  1. for loop

You can use a for loop to obtain the value of a two-dimensional array . In the outer loop, the for statement iterates through each sub-array in the main array. Within the inner loop, you can use a for loop to iterate over the keys and values in each sub-array.

Sample code:

"; } ?>
Copy after login

Result:

Maths: 85 English: 82 Science: 90
Copy after login
Copy after login
  1. while loop

You can use a while loop to obtain the value of a two-dimensional array . In the outer loop, use a while statement to loop through each sub-array in the main array. Within the inner loop, you can use another while loop to iterate over the keys and values in each sub-array.

Sample code:

"; $row++; } ?>
Copy after login

Result:

Maths 85 English 82 Science 90
Copy after login

Summary

The above are three methods of obtaining two-dimensional array values. Among them, the foreach loop is suitable for traversing small two-dimensional arrays, while using the for loop is suitable for larger arrays. The use of while loops is suitable for situations where other operations need to be performed within the inner loop.

The above is the detailed content of How to get the value of a two-dimensional array 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!