skip to Main Content

I want to make a triangle like this with php , but i try in local still fail how to code like the example above

<?php
    $star=10;
    for($a=1; $a<=$star; $a++){
    for($c=$star; $c>=$a; $c-=1){
        echo "*";
    }
    echo "<br>";
    }
?>

I have value 1225441. How to create output like this with looping php?

1000000
200000
20000
5000
400
40
1

3

Answers


  1. You had the right idea with a for loop.
    You just need to know how long your input is, and pad the output with the length of your input, gradually getting smaller with each iteration.

    <?php
    # Replace this with whatever is the source of your input.
    $input = '1225441';
    
    # get total number of characters in input
    $length = strlen($input);
    # foreach character in input
    for ($i = 0; $i < $length; $i++) {
        # echo the character as many times as $length - $i - 1.
        echo $input[$i] . str_repeat(0, $length - $i - 1) . '<br>';
    }
    

    This creates the output of:

    1000000
    200000
    20000
    5000
    400
    40
    1
    
    Login or Signup to reply.
  2. If it’s hard for you to think about how to do it with PHP, then think first about the general way to do it, I mean the algorithm. You can represent it with a flow diagram. Then, you just need to translate it to PHP code.

    And the result it can be something like this:

    <?php
    
    $n = 1225441;
    
    $string = '' . $n; //Let`s have a string for better use string functions
    
    for ($c = 0, $len = strlen($string); $c < $len; $c++) {
        echo substr($string, $c, 1);
        for ($k = $len - 1; $k > $c; $k--) {
            echo '0';
        }
        echo '<br />';
    }
    
    Login or Signup to reply.
  3. Yet another solution as a one-liner.

    $n = '1225441';
    array_reduce(str_split($n),fn($c,$i)=>$c-(print $i.str_repeat('0',$c)."n"),strlen($n)-1);
    

    Output

    1000000
    200000
    20000
    5000
    400
    40
    1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search