Repeat a command multiple times???

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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Repeat a command multiple times???

Post by Chris Corbyn »

Hi,

does anyone know a way to do something X amount of times in sequence, for example, if I have an array of numbers and I want to print a star, *, X amount of times where X is the number.

Code: Select all

$array = array(4, 7, 9, 10, 56, 78, 99);

echo '*' * $array[0]; /*Not the way to do it but just to indicate what I'm trying to do*/
So in the case above a star is printed times. What's the correct way to do this?

Thanks
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

Code: Select all

<?php
foreach($array as $value){
    for($i=0;$i<$value;$i++) {echo '*';}
}
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Re: Repeat a command multiple times???

Post by d3ad1ysp0rk »

Code: Select all

$array = array(4, 7, 9, 10, 56, 78, 99);
$x = $array[0];
for($i=0;$i<$x;$i++){
echo "*";
}
Sycor
Forum Newbie
Posts: 8
Joined: Fri Jun 11, 2004 3:54 am

Post by Sycor »

To loop through each element in the array you could always use this...

Code: Select all

<?php

$array = array(4, 7, 9, 10, 56, 78, 99);

for ($element = 0; $element < sizeof($array); $element++)
{
for ($count = 0; $count < $array[$element]; $count++)
{
echo "*";
}
}

?>
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

uhh that's what mine did but ill change it to:

Code: Select all

<?php
foreach($array as $value){ 
  str_repeat("*",$value);
} 
?>

?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Thanks everyone :-D

Sorry I abandoned this topic, got busy working on something else :-/
Post Reply