Tuesday 17 July 2018

Loop Through Letters in a String with PHP

Loop Through Letters in a String with PHP

Iterating through a string to get each letter can be easily achieved with PHP. The example below shows how this can be done with a for loop:

  1. $string = "HelloWorld";  
  2.   
  3. for ($i=0; $i<strlen($string); $i++) {  
  4.     echo $string[$i].".";  
  5. }  
  6.   
  7. // Outputs: H.e.l.l.o.W.o.r.l.d.  
Notice how we reference the individual letters like we would an array element. This also means we can get the letter at a certain point by referencing the letters index like so:

  1. $string = "HelloWorld";  
  2.   
  3. echo $string[4];  
  4.   
  5. // Outputs: o  

0 comments:

Post a Comment