Php Loop Array

PHP – Loop through Characters in String

To iterate over each character in a string, there are following two approaches.

  1. In PHP, the foreach is used to loop arrays. The foreach loop passes the value of the current element which is assigned to $value while array pointer is moved to the next element. In the next loop, the next element will be processed and this will go on until the last element. As you are using a foreach loop with an array, rather having a counter that goes until proven false (like i) the foreach loop goes on looping unless it has used all values in the array. A foreach PHP example with a.
  2. PHP – Loop through Characters in String. To iterate over each character in a string, there are following two approaches. Approach 1: Using strsplit and foreach. Split the string into an array of characters using strsplit function.

Lesson 12 - Arrays and loops in PHP Filling an array using loops. Loops are widely used for automatizing array manipulations. Usually, there are lots of. Printing an array using loops. We now have an array filled with 100 numbers. However, we don't usually generate arrays. PHP array functions.

Approach 1: Using str_split() and foreach

Key
  1. Take a string.
  2. Split the string into an array of characters using str_split() function.
  3. Use a looping statement like for loop or while loop, to iterate over each of the element (character) in the array.
Php

Approach 2: Using index and for loop

  1. Take a string.
  2. Initialize index to 0.
  3. Define for loop that iterates when the index is less than string length.
    1. Access character using string and index.

Example : For Each Character in String using str_split() and foreach

Php loop array with indexPhp Loop Array

In this example, we will take a string, say “apple”, and iterate over each character of the string using str_split() function and foreach statement.

Php Loop Array

PHP Program

Php Foreach Next

Program Output

Php Loop Array Key

Example : For Each Character in String using Index and For Loop

In this example, we will take a string, say “apple”, and iterate over each character of the string using index, that increments for each iteration, and for loop statement.

PHP Program

Array Loop In Php

Program Output

Conclusion

In this PHP Tutorial, we learned how to iterate or loop for each character in a string, using different ways in PHP.