Hugh Lashbrooke

Product manager by day, tabletop game designer by night.

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:


View this gist on GitHub

23 responses to “Loop through each character in a string in PHP”

  1. Joel Day Avatar
    Joel Day

    Rather than using substr you could just use $str[$i] which should be a little faster 🙂

    1. Hugh Lashbrooke Avatar
      Hugh Lashbrooke

      Thanks for the input, but I don’t think that would work because $str isn’t an array (unless there’s something I’m missing).

      1. naresh Avatar
        naresh

        strings are treated/considered as array of char elements 🙂

        1. Hugh Lashbrooke Avatar
          Hugh Lashbrooke

          Yeah – after posting that above comment and actually learned exactly that. It’s a handy thing to know for the future!

        2. Andrea Avatar
          Andrea

          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

      2. TheMyth Avatar
        TheMyth

        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

    2. christian Avatar
      christian

      not recommended bro.

      you might get ‘Uninitialized string offset’ for the unexpected user input.

      Thanks.

    3. christian Avatar
      christian

      andrea

      try running your code again,
      you miss the 0 value. hehehehe

  2. NIikhil Zachariah Avatar
    NIikhil Zachariah

    Thank You So much

  3. NIikhil Zachariah Avatar
    NIikhil Zachariah

    thank U!!!!!!!!!!!!!!!

  4. TempleClause Avatar
    TempleClause

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

    But thanks for the rest 😀

  5. Sumit Gupta Avatar
    Sumit Gupta

    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.

  6. christian Avatar
    christian

    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.

  7. christian Avatar
    christian

    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. Christian Avatar
      Christian

      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].

  8. christian Avatar
    christian

    i mean
    $input = ‘0123’;//wehehehe

  9. D'angelo Williams Avatar
    D’angelo Williams

    Thank you, this was exactly what I needed. You da best

  10. Ali Avatar
    Ali

    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");

  11. ram Avatar
    ram

    $str = “String to loop through”;

  12. Joachim Coyoca Avatar
    Joachim Coyoca

    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 🙂

  13. Sajjad Avatar
    Sajjad

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

  14. Chris Nasr Avatar
    Chris Nasr

    You should really be using mb_strlen, not strlen, unless your intention is to traverse the string as if it were raw data.

  15. Shashidhar. A. R Avatar
    Shashidhar. A. R

    Hello sir…
    I have one doubt.
    Define stringwalk?

Leave a Reply

Your email address will not be published. Required fields are marked *