Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@alexbecor alexbecor commented Oct 23, 2014

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

Shouldn't there be $i < $strlen?

@brunoais

This comment has been minimized.

Copy link

@brunoais brunoais commented May 1, 2015

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

@ideaguy3d

This comment has been minimized.

Copy link

@ideaguy3d ideaguy3d commented Jul 31, 2018

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
You can’t perform that action at this time.