How is this done in PHP? For example, I have the string "I can read", if I want to search through each member of the string, how do I go about this?
Thanks.
[SOLVED] Looping Through a String
Moderator: General Moderators
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
$string = "I can read";
$len = strlen($string);
for($x = 0; $x < $len; $x++)
{
echo $string{$x}."<br />\n";
}Sorry, not sure what I'm doing wrong here.
Let's say I have the string: $string = "Hello";
I have tried to just echo out "$string{0}", but that doesn't seem to work. Also tried to do:
In order to do a switch with the FIRST member of the string, yet when I know for a fact the string is NOT empty, it comes up empty. Anything obviouse I am doing wrong?
Let's say I have the string: $string = "Hello";
I have tried to just echo out "$string{0}", but that doesn't seem to work. Also tried to do:
Code: Select all
switch($name{0})- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
<?php
$string = "Hello";
// for the first one
echo $string{0};
// for the second one
switch($string{0})
{
case 'H':
echo 'H found';
break;
default:
echo 'uncaught: '.$string{0}.'('.ord($string{0}).')'."\n";
break;
}
// alternate to second one
switch(ord($string{0}))
{
case ord('H'):
echo 'H found';
break;
default:
echo 'uncaught: '.$string{0}.'('.ord($string{0}).')'."\n";
break;
}
?>Well, it was not anything to do with the code here, it was rather the fact that I had a form, and I did a switch looking for the first letter in the input taken from the form, but I only searched for the lowercase letters, so when I typed it in caps it went strait to the default. So I just used strtolower().
Not much to help future users
.
Not much to help future users