0

i have code :

<?php
$number =9;
$number2 = $number / 2;
    for ($b=0; $b<=$number2; $b++){
        for ($i=$number; $i>=1; $i--){
            echo $i;
        }
        echo "<br/>";
        for ($a=1; $a<=$number; $a++)
        {
        echo $a;
    }
    echo "<br/>";
}
?>

I want the result like this .

987654321
123456789
987654321
123456789
987654321
123456789
987654321
123456789
987654321

why if i put odd number like 9 , why always the result 10 loop ?

1
  • 4
    Because loop is starting from 0 so total iterations 0,1,2,3,4 that's 5 times and you have two inner loops so 5*2 = 10 loop Commented May 5, 2018 at 17:26

2 Answers 2

3

You have two loops in a loop, therefore you'll always get an even number of lines.

You don't actually need that structure, see:

$number=9;
$k=0;
$sum=1;
for($i=1; $i<=$number; $i++) {
    for($j=1; $j<=$number; $j++) {
        $k+=$sum;
        echo $k;
    }
    echo '<br>';
    //Sum once again so in the next iteration $k is 0 or 10
    $k+=$sum;
    //Invert the sign of $sum so in the next iteration it substracts, and then adds, and so on
    $sum*=-1;
}

Also note that going from 0 to $number inclusive (lower or equal comparation) you'll get one iteration more (from 0 to 9 there are 10 whole numbers).

Sign up to request clarification or add additional context in comments.

3 Comments

@ZakarioLesrahmanto - If it worked for you, you should accept the answer so other users know it's been solved.
Hi magnus , the result its start 123456789 . i want first row is 987654321 , how i get it ?
Start from $k=10 and $sum=-1. Analyze the code, it's really simple!
0

Solve with this code , thx Gabriel.

$number=9;
$k=0;
$sum=1;
for($i=1; $i<=$number; $i++) {
    for($j=1; $j<=$number; $j++) {
        $k+=$sum;
        echo $k;
    }
    echo '<br>';
    //Sum once again so in the next iteration $k is 0 or 10
    $k+=$sum;
    //Invert the sign of $sum so in the next iteration it substracts, and then adds, and so on
    $sum*=-1;
}

4 Comments

I didn't do anything to help you. It was all Gabriel. And I must say that it's quite disrespectful towards Gabriel (who was nice enough to spend his time helping you) to post his answer as your own instead of accepting his.
Actually, I see that you haven't accepted one single answer on any of your questions, though you got plenty of answers. That's very disrespectful. If people take their time helping you, you could at least recognize it.
i'm sorry for not concentrating, in here it so late night , now in my country is 3AM . T_T
...and still you haven't accepted Gabriels answer. =/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.