Home > Mobile >  how to two array set foreach loop php
how to two array set foreach loop php

Time:05-19

$color_arr = array("red","green","white");

 $list_arr_two = array("a","b","c","d","e","f");

for ex -:  a = red;
       b = green;
       c = white;
       d = red;
       e = green;
       f = white;

I just need to get repeat color once all array color repeated completed.

CodePudding user response:

please try the below code:

<?php
  $color_arr = array("red","green","white");

  $list_arr_two = array("a","b","c","d","e","f","sd");
  $i=0;
  $color_length = count($color_arr) -1 ;
  foreach($list_arr_two as $key=>$val)
  {
    echo $colorCode = $color_arr[$i];
    echo "<br/>";
    $i  ;
    if($i > $color_length)
    {
      $i =0;
    }
  }
?>

CodePudding user response:

Simple loop with condition to reset the index for using color array.

<?php
$c = ["red","green","white"];
$l = ["a","b","c","d","e","f"];

$r = [];
$j = 0;
for ($i = 0; $i < count($l); $i  ) {
    $r[$l[$i]] = $j === count($c) ? $c[$j = 0] : $c[$j];
    $j  ;
}

print_r($r);

/* output
Array
(
    [a] => red
    [b] => green
    [c] => white
    [d] => red
    [e] => green
    [f] => white
)
*/

CodePudding user response:

Use this custom function to get result

$color_arr = array("red","green","white");
$list_arr_two = array("a","b","c","d","e","f");
print_r(ArrayMap($color_arr,$list_arr_two));

function ArrayMap($color_arr,$keyarray){
    $newarr=array();
    $total_array = count($color_arr);
    foreach ($keyarray as $key => $value) {
        $newarr[$value] = $color_arr[$key%$total_array];
    }
    return $newarr;
}
  •  Tags:  
  • php
  • Related