how to creat a good loop

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
cybershot
Forum Commoner
Posts: 29
Joined: Thu Jul 24, 2008 12:06 pm

how to creat a good loop

Post 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.
Last edited by cybershot on Thu Jul 24, 2008 12:35 pm, edited 1 time in total.
User avatar
ghurtado
Forum Contributor
Posts: 334
Joined: Wed Jul 23, 2008 12:19 pm

Re: how to creat a good loop

Post 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
cybershot
Forum Commoner
Posts: 29
Joined: Thu Jul 24, 2008 12:06 pm

Re: how to creat a good loop

Post 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?
User avatar
deejay
Forum Contributor
Posts: 201
Joined: Wed Jan 22, 2003 3:33 am
Location: Cornwall

Re: how to creat a good loop

Post by deejay »

http://uk.php.net/manual/en/function.strlen.php

and check http://uk.php.net/manual/en/control-structures.for.php for your loop. maybe

Code: Select all

 
 
$hi = 'Hello';
 
for ($i = 1; $i <= 10; $i++) {
    echo $hi[$i];
}
 
 
Quixotic
Forum Newbie
Posts: 2
Joined: Fri Jul 25, 2008 3:42 am

Re: how to creat a good loop

Post 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.
Quixotic
Forum Newbie
Posts: 2
Joined: Fri Jul 25, 2008 3:42 am

Re: how to creat a good loop

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

Code: Select all

May suit your purposes better
Post Reply