Pavel
Pavel

Reputation: 21

PHP forward and backward for loop verse

I could make first verse to write but I want next verse to be written backwards however I can't do it.

<?php
$russian[]="En";
$russian[]="liten";
$russian[]="vektor";
$russian[]="ar";
$russian[]="ett";
$russian[]="exempel";
$russian[]="pa";
$russian[]="och";
$russian[]="falt";
for ($soviet=0;$soviet<sizeof($russian);$soviet++)
echo $russian[$soviet]." ";
for ($soviet=5;$soviet<sizeof($russian);$soviet=$soviet-1)
echo $russian[$soviet]." ";
?>

Upvotes: 1

Views: 258

Answers (4)

mario
mario

Reputation: 145482

If you have such a small array, I would not bother with constructing the right for conditions.
Instead use:

foreach (array_reverse($russian) as $word) {

Upvotes: 1

Marc B
Marc B

Reputation: 360762

I'm guessing this:

for ($soviet=count($russian);$soviet>0;$soviet--)

Not sure what you mean by verse, though. You want print out that array twice, once forward, and once backward, so you end up with

En liten vektor ar ett exempel pa och falt falt och pa exempel ett ar vektor liten En

?

Upvotes: 1

yitwail
yitwail

Reputation: 2009

try this,

for ($soviet=sizeof($russian)-1; $soviet >= 0; $soviet--)
  echo $russian[$soviet]." ";

you have to test for >= 0, because the first word is in $russian[0]

Upvotes: 1

rid
rid

Reputation: 63542

If what you want is to display the words from the last to the first, you could use:

for ($soviet = count($russian); $soviet > 0; --$soviet)

Upvotes: 1

Related Questions