Skip to content

Instantly share code, notes, and snippets.

@hlashbrooke
Created October 16, 2014 12:23
Show Gist options
  • 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
?>
@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