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:

$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
}

Once I had the loop set up I simply added an is_ numeric() check and inserted a break command the first time the check returned false – here is my use case:

$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

Tags: , ,

4 Responses to “Loop through each character in a string in PHP”

  1. Joel Day July 9, 2012 at 10:39 pm #

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

    • Hugh Lashbrooke July 10, 2012 at 2:43 pm #

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

      • naresh August 22, 2012 at 3:28 am #

        strings are treated/considered as array of char elements :)

        • Hugh Lashbrooke August 22, 2012 at 2:43 pm #

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

Leave a Reply