How to traverse string array in php

PHPz
Release: 2023-04-20 14:57:59
Original
985 people have browsed it

PHP is an open source scripting language that is widely used for website development and command line scripting on web servers. In PHP, working with arrays is a very common task. But sometimes it is necessary to traverse a string array, so how to traverse a string array in PHP? This article will introduce it in detail.

  1. for loop traversal

Using a for loop is the most basic traversal method. You can use the count() method to get the array length, and then use a for loop to traverse the array elements.

Sample code:

<?php
    $array = ["Hello", "World", "!"]; 
  
    //使用for循环遍历数组
    for($i = 0; $i < count($array); $i++) {
        echo $array[$i] . " ";
    }
?>
Copy after login

Output result:

Hello World !
Copy after login
Copy after login
Copy after login
  1. foreach loop traversal

Using foreach loop is the most commonly used in PHP One of the traversal methods. The foreach loop can be used to iterate over any type of array, including string arrays.

Sample code:

<?php
    $array = ["Hello", "World", "!"];
  
    //使用foreach遍历数组
    foreach($array as $value) {
        echo $value . " ";
    }
?>
Copy after login

Output result:

Hello World !
Copy after login
Copy after login
Copy after login
  1. while loop traversal

while loop can also be used to traverse arrays. You can use the list() function to convert the values ​​in an array into variables and iterate over them.

Sample code:

<?php
    $array = ["Hello", "World", "!"];
  
    //使用while循环遍历数组
    reset($array);
    while(list(, $value) = each($array)) {
        echo $value . " ";
    }
?>
Copy after login

Output result:

Hello World !
Copy after login
Copy after login
Copy after login

Summary:

The above are three common methods for traversing string arrays in PHP. In the actual development process, different methods can be selected according to the actual situation. The for loop is suitable for situations where you need to access array subscripts, the foreach loop can traverse associative arrays more conveniently, and the while loop can be used for different types of arrays. Either way, you can easily iterate over an array of strings.

The above is the detailed content of How to traverse string 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template