skip to Main Content

I have this attempt using foreach function.

<?php

$persons = array("John","Kevin","Daniel");
$cars = array("Volvo", "BMW", "Toyota");
$colors = array("red", "blue", "green");
foreach($persons as $person){
  foreach($cars as $car){
    foreach($colors as $color){
      echo "I'm $person and my car $car is color <span style='color:$color'>$color</span>. <br>";
    }
  }
}

?>

What I want

What I want

What I get

What I get

I’m not quite good at php, so where do you think I’m wrong?
Any approach?

3

Answers


  1. It would be much easier using a for-loop. Here is my code please let me know if it works for you.

    <?php
    
    $persons = array("John","Kevin","Daniel");
    $cars = array("Volvo", "BMW", "Toyota");
    $colors = array("red", "blue", "green");
    
    $count = count($persons);
    
    for ($i = 0; $i < $count; $i++) {
      $person = $persons[$i];
      $car = $cars[$i];
      $color = $colors[$i];
    
      echo "I'm $person and my car $car is color <span style='color:$color'>$color</span>. <br>";
    }
    
    ?>
    
    Login or Signup to reply.
  2. you can write code like this :

    $persons = array("John","Kevin","Daniel");
    $cars = array("Volvo", "BMW", "Toyota");
    $colors = array("red", "blue", "green");
    
    foreach ($persons as $key => $val){
        echo "I'm $val and my car $cars[$key] is color <span style='color:$colors[$key]'>$colors[$key]</span>. <br>";
    }
    
    Login or Signup to reply.
  3. That’s because you are iterating over the three arrays inside each foreach statement, this gives you 3x3x3 combinations.

    Since you guarantee that the three arrays are same length, you can iterate just over one of them and use the index:

    foreach ($persons as $index => $person) {
        $car = $cars[$index];
        $color = $colors[$index];
    
        echo "I'm $person and my car $car is color <span style='color:$color'>$color</span>. <br>";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search