Skip to content

Instantly share code, notes, and snippets.

@hlashbrooke
Created October 16, 2014 12:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hlashbrooke/ee208fb8be43d23da5a9 to your computer and use it in GitHub Desktop.
Save hlashbrooke/ee208fb8be43d23da5a9 to your computer and use it in GitHub Desktop.
PHP: Loop through each character in a string
<?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
}
?>
<?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
?>
@alexbecor
Copy link

"for( $i = 0; $i <= $strlen; $i++ ) "

Shouldn't there be $i < $strlen?

@brunoais
Copy link

brunoais commented May 1, 2015

Why use substr()? Why not use the array-like syntax?

@ideaguy3d
Copy link

There are always like 20-50 solutions to a problem. This 1 is cool ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment