Thembi Thembi - 4 months ago 18
PHP Question

how to write a nested php loop that draws an image with few lines of code?

How best can i solve this with less code as possible below is the problem

*****

****x

***xx

**xxx

*****

**xxx

***xx

****x

*****


this is my code that i want to improve:

<?php


for ($i=0; $i < 5 ; $i++) {
if($i >= 1 & ($i <= 3))
{
for ($t=0; $t < 5-$i ; $t++)
echo "*";
for ($t=0; $t < $i ; $t++)
echo "x";
}

else
for ($j=0; $j < 5 ; $j++)
echo "*";
echo "<br/>";
}

for ($f=1; $f < 5 ; $f++) {
for ($j=0; $j < $f+1; $j++)
echo "*";
for ($v=3; $v>= $f; $v--)
echo "x";
echo "<br/>";

}
?>

Answer Source

To create string with repeated symbols you can use str_repeat. Using this function your code can be simplified to:

$num = 5;
for ($i = $num; $i > 1; $i--) {
    echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}

echo str_repeat('*', $num) . PHP_EOL;

for ($i = 2; $i <= $num; $i++) {
    echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}

Even if you cannot use php core functions, you can write you own function to create same results as str_repeat:

function createLine($starsCount, $XCount) {
    $result = '';

    for ($i = 0; $i < $starsCount; $i++) {
        $result .= '*';
    }
    for ($i = 0; $i < $XCount; $i++) {
        $result .= 'x';
    }

    return $result;
}

And rewrite code as:

$num = 5;
for ($i = $num; $i > 1; $i--) {
    echo createLine($i, $num - $i) . PHP_EOL;
}

echo createLine($num, 0) . PHP_EOL;

for ($i = 2; $i <= $num; $i++) {
    echo createLine($i, $num - $i) . PHP_EOL;
}