Page 1 of 1

Looping Through a String

Posted: Wed Jun 09, 2004 3:17 pm
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.

Posted: Wed Jun 09, 2004 3:19 pm
by feyd

Code: Select all

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

for($x = 0; $x < $len; $x++)
{
  echo $string{$x}."<br />\n";
}

Posted: Sat Jun 26, 2004 2:37 am
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?

Posted: Sat Jun 26, 2004 2:46 am
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;
}


?>

Posted: Sat Jun 26, 2004 2:53 am
by Zorth
Wow, so sorry to waste forum space because I just found out the problem :p.

Posted: Sat Jun 26, 2004 2:54 am
by feyd
for future viewers, what was it?

Posted: Sat Jun 26, 2004 3:17 am
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.