Skip to content

Instantly share code, notes, and snippets.

@ideaguy3d
Forked from hlashbrooke/function.php
Created July 31, 2018 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ideaguy3d/43fab01b0e7c2061f4775bc63fbd5ed0 to your computer and use it in GitHub Desktop.
Save ideaguy3d/43fab01b0e7c2061f4775bc63fbd5ed0 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
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment