Home > database >  Getting these paterns using for loop in PHP
Getting these paterns using for loop in PHP

Time:09-09

I wanted to create a for loop that would make a pattern like this.

* two tree four five
one * tree four five
one two * four five
one two tree * five
one two tree four *

* * tree four five
one * * four five
one two * * five
one two tree * *

* * * four five
one * * * five
one two * * *

* * * * five
one * * * *

* * * * *

Instead I end up finding this How to get these patern using for loop

The guys are using JavaScript:

const temp = ["one","two","three","four","five"];
let arrayResult = []
for(let i = 0; i< temp.length; i  ){
    for(let j = 0; j< temp.length - i; j  ){
        let tempArr = temp.slice();
        let stars = Array(i 1).fill('*')
        tempArr.splice(j, i 1, ...stars);
        arrayResult.push(tempArr);
    }}

I wanted to pull this of using php but I can't seem to get it work even with array_splice()

$temp = array("one","two","three","four","five");
$arrayResult = array();
for($i = 0; $i< count($temp); $i  ){
    for($j = 0; $j< count($temp) - $i; $j  ){
        $tempArr = $temp.slice();
        $stars = Array($i 1).fill('*')
        $tempArr.splice($j, $i 1, ...$stars);
        $arrayResult [] = $tempArr;
    }}

CodePudding user response:

You can do it like below:

<?php
$temp = array("one","two","three","four","five");
$arrayResult = array();
for($i = 0; $i< count($temp); $i  ){
    for($j = 0; $j< count($temp) - $i; $j  ){
        $tempArr = $temp; //assign original array to temp variable
        $newArray[$i 1] = '*'; //create a new star array
        array_splice($tempArr,$j, $i 1,$newArray); //fill the stars into temp array
        $arrayResult [] = $tempArr; //assign temp array to final output array
    }

}
print_r($arrayResult);

Output: https://3v4l.org/9KRYJ

Note: If you run the script and do console.log of each variable, you can easily understand what's going on and how to convert it to PHP code. I did the same way.

CodePudding user response:

$template=explode(' ','one two tree four five');
//$template=['one', 'two', 'tree', 'four', 'five'];
for($i=5;($i-->0);)for($pos=0;$pos  <=$i;)  $res[]=array_replace($template,array_fill($pos-1,5-$i,'*') );


echo '<pre>';
//print_r($res);
var_dump($res);
echo '</pre>';

CodePudding user response:

<?php
        
$result = [];
$temp = ["one", "two", "three", "four", "five"];

for ($i = 0; $i < count($temp); $i  ) {
    for ($j = 0; $j < count($temp) - $i; $j  ) {
        $tempArr = $temp;
        $stars[$i 1] = "*";
        array_splice($tempArr, $j, $i 1, $stars);
        array_push($result, $tempArr);
    }
}

echo "<pre>";
print_r($result);
echo "</pre>";

Hope this helps!

  •  Tags:  
  • php
  • Related