[SOLVED] Looping Through a String

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Looping Through a String

Post by Zorth »

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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$string = "I can read";
$len = strlen($string);

for($x = 0; $x < $len; $x++)
{
  echo $string{$x}."<br />\n";
}
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Post by Zorth »

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:

Code: Select all

switch($name&#123;0&#125;)
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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

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;
}


?>
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Post by Zorth »

Wow, so sorry to waste forum space because I just found out the problem :p.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

for future viewers, what was it?
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Post by Zorth »

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 :P.
Post Reply