Reputation: 3
Just want to print the pattern by giving input through array
<?php
$a=array(2,4,1,6);
foreach($a as $a1){
for($row=1;$row<=count($a1);$row++){
for($col=1;$col<=count($a1);$col++){
echo "*";
}
echo "<br>";
}
}
?>
I'm using foreach loop to pass the values one by one but that's not working?
Upvotes: 0
Views: 185
Reputation: 404
below can be used to achieve your expected outcome. (Assuming that the the pattern you want to create is given as the input array)
$a=array(2,4,1,6);
foreach($a as $a1){
for($col=1;$col<=$a1;$col++){
echo "*";
}
echo "<br>";
}
I want to print the mirror image some what like this
*
*
* *
* *
* *
** *
****
Upvotes: 0
Reputation: 3512
count($a1)
will always == 1
.
In the foreach
loop $a1
will take the values of the members of the array, so $a1 == 2
on the first loop, 4
on the second, and so on. $a1
is a number, so using count($a1)
doesn't make any sense.
The second loop (the for
loop) is presumably to print the same number of asterisks as the value of $a1
. The value remember, not the count, the count is how many members an array or object has. So instead of $row<=count($a1)
you need to use row<=$a1
.
The third loop is unnecessary. Unless you're printing in 3 dimensions. Just move the print
function inside the first for
loop and delete it.
Upvotes: 0
Reputation: 23968
You can use str_pad to avoid all the excessive looping.
$a = array(2,4,1,6);
foreach($a as $a1){
echo str_pad("", $a1, "*") . "<br/>\n";
}
Upvotes: 1