Loop through each character in a string in PHP

The other day I was working on a project that required me to extract a numeric ID from the current page’s URL. The problem was that the ID could either be at the end of the URL string or in the middle, depending if there were any parameters added on or not. Here is how I worked around the problem by looping through each character of the string.

Because the first part of the URL was formatted normally I could use a combination of strpos() and substr() to find the part of the string that contained the ID as well as all the characters that followed it (I could have used regex here, but I prefer to avoid using it if I can help it). This still left me with the problem of getting the ID out of that string, as the actual number could be any length. Luckily for me, the ID was immediately followed by a non-numeric character, so I came up with a solution where I could loop through each character in the string and use each one for the required ID, but stop the loop when I hit the first character that was not a number. In the interest of sharing some useful code, here is the simple snippet that I used to loop through the string along with my use case:


<?php
$str = "String to loop through"
$strlen = strlen( $str );
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr( $str, $i, 1 );
// $char contains the current character, so do your processing here
}
?>

view raw

function.php

hosted with ❤ by GitHub


<?php
$str = "123?param=value"
$strlen = strlen( $str );
$id = "";
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr( $str, $i, 1 );
if( ! is_numeric( $char ) ) { break; }
$id .= $char;
}
// $id now contains the ID I need, in this case: 123
?>

view raw

use_case.php

hosted with ❤ by GitHub

23 Thoughts

        1. You can use $str{$i} which worked for me in looking at a specific character is a string.

          Example:
          Code:
          $string = ‘0123’;
          for ($i=0; $i < strlen($string); $i++)
          {
          echo $i."=".$string{$i}."”;
          }
          Result:
          0=0
          1=1
          2=2
          3=3

      1. I want to simply validate a name where there should be no numbers,
        eg: Harr8y = false
        Im new and not very good at PHP, what would be the best way to go through each character
        as ctype_digit does not work because it checks the whole string

  1. I think rather than using
    for( $i = 0; $i <= $strlen; $i++ ) {
    you should use < $strlen

    But thanks for the rest 😀

  2. Though it is too late, but PHP has inbuilt function of str_split that can be used to iterate after converting string to array. One of example there has function that works for Unicode character, as default str_split of above mention method won’t work there.

  3. Joel Day, naresh
    try testing

    if(char[0] == ‘ ‘)….

    if the char contains 0 values it return as a null value.

    Hugh Lashbrooke saves the day. wehehehe
    though its already been a year. Thank you bro.

  4. i mean
    what if the input is
    $input = 0123;
    for($i = 0;$i <=strlen($input );$i++ ){
    echo $input[$i]; //when it goes to the first array value it would detect null value. program noticed. not good.
    }
    Thanks again.

    1. You can not iterate through a number the same way you can iterate through a string. If you turn $input into a string first then you can use echo $input[$i].

  5. Here is my solution to the problem you had Hugh,
    I tried to obvious method to me atleast.
    is there difference in how you it and mine in terms of performance?

    //return id from a string
    function GetID($str)
    {

    $length=strlen($str);
    $id=””;
    for ($i=0; $i < $length; $i++)
    {
    if(is_numeric($str[$i]))
    {
    $id=$id.$str[$i];
    }
    else
    {
    break;
    }
    }
    return $id;
    }
    echo " The ID is = ".GetID("1235?valu");

  6. what if i had a table visitor contains a field of id, name, year and department and another table of department which contains a field of id, year and department_name…. the department value would be BSHRM AND BSCRiM and etc.. in every entry of visitor, how could i convert every department into an integer??? for example… first loop would be BSHRM will be equal to 1, and second loop BSHRM equal to 2, until all BSHRM will finish to convert into number….. someone there.. please help me… heres my email..for those who are willing to help.. [email protected]…. thank you 🙂

  7. $str = “123456789”
    $len = strlen( $str );
    for( $i = 0; $i <= $len; $i++ ) {
    $a.=$i;
    }
    // Output
    /*
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    */
    😀

Leave a Reply