In PHP, array is a very commonly used data type. When we deal with large amounts of similar data, arrays can facilitate our storage and manipulation. Among them, array traversal is a process that we often operate in daily use. Next, I will introduce how to traverse arrays in PHP.
In PHP, you can use thecount()
function to get the length of the array. Therefore, when using a for loop to iterate over an array, the length of the array can be used for the number of loops. The code is as follows:
$fruits = array("apple", "banana", "orange", "watermelon"); $length = count($fruits); for ($i = 0; $i < $length; $i++) { echo $fruits[$i] . " "; }
The above code uses a for loop, and the number of loops is the length of the arraycount($fruits)
. In the loop body, use$fruits[$i]
to get the element with the specified subscript in the array and print it to the screen.
If you don’t need to access the subscript of the array, you can useforeach
to loop through the array.foreach
The loop will automatically take out each element in the array one by one and assign it to the defined variable. The code is as follows:
$fruits = array("apple", "banana", "orange", "watermelon"); foreach ($fruits as $fruit) { echo $fruit . " "; }
In the above code, theforeach
loop will automatically take out each element in the array$fruits
one by one and assign it to$fruit
variable. In the loop body, directly use the$fruit
variable to get the value of the current element and print it to the screen.
In PHP, you can use associative arrays to store a set of key-value pairs. Like a normal array, it is relatively simple to loop over an associative array usingforeach
. But it should be noted that when defining a loop variable, you need to use two variables, one representing the key and one representing the value. The code is as follows:
$fruits = array("apple" => 5, "banana" => 4, "orange" => 3, "watermelon" => 7); foreach ($fruits as $fruitName => $fruitCount) { echo $fruitName . " has " . $fruitCount . " pieces "; }
In the above code, theforeach
loop will automatically take out each key-value pair in the array$fruits
one by one, and assign the key name to$fruitName
variable, the value is assigned to the$fruitCount
variable. In the loop body, directly use the$fruitName
and$fruitCount
variables to obtain the current key name and value respectively, and print them to the screen.
Summary
The above are the three methods of array traversal in PHP, among which usingforeach
loop traversal is the most commonly used method, especially suitable for traversing associative arrays. When traversing an array, you need to flexibly choose the appropriate method according to specific needs in order to improve the efficiency of the code.
The above is the detailed content of How to traverse arrays in php. For more information, please follow other related articles on the PHP Chinese website!