Page 1 of 1
how to creat a good loop
Posted: Thu Jul 24, 2008 12:09 pm
by cybershot
I wanted to creat a loop to say hello. I tried this
Code: Select all
$hi = "hello";
for($i = 0; $i < 10; $i++)
{
echo($hi[$i])
}
i started getting mixed results. I did get one version working but what i know about loops tells me the code is wrong even though it apears to be working.
Re: how to creat a good loop
Posted: Thu Jul 24, 2008 12:12 pm
by ghurtado
There are a couple of things wrong with that loop.
- You forgot the dollar sign in front of the "I" variable
- The string is only 5 characters long but you iterate up to 10 times, use strlen() to get the length of the string
Re: how to creat a good loop
Posted: Thu Jul 24, 2008 12:34 pm
by cybershot
I don't know php. I was working from what I know about csharp. I don't know what strlen() is or how to use it. Can you write a better loop for me?
Re: how to creat a good loop
Posted: Fri Jul 25, 2008 2:55 am
by deejay
Re: how to creat a good loop
Posted: Fri Jul 25, 2008 4:39 am
by Quixotic
Code: Select all
<?php
$hi = 'Hello';
$length = strlen($hi)-1;
for($i=0;$i<=$length;$i++)
{
echo $hi[$i];
}
?>
Should suffice
In php strings can be treated as arrays for this purpose i.e. you can access elements like $hi[1]. However, they are not actually arrays. Usually with arrays a foreach($array as $variable){echo $variable;} type loop is used. This does not work with strings.
Re: how to creat a good loop
Posted: Fri Jul 25, 2008 4:58 am
by Quixotic
actually something like:
Code: Select all
$hi = 'Hello';
$hiArray = preg_split('//', $hi, -1,PREG_SPLIT_NO_EMPTY);
print_r($hiArray);
foreach($hiArray as $letter)
{
echo $letter;
}