1

How to use Foreach on two or more php arrays?

My arrays are $boardType, $hotelPrice and $hotelName

Solution is to add $index in the other arrays as suffix

<?php foreach ($hotelName as $index => $name):?>
<div>
<p><?php echo $name;?></p>
<p><?php echo $hotelPrice[$index];?></p>
<p><?php echo $boardType[$index];?></p>
</div>
<?php endforeach?>
4
  • 1
    you are asking about nested foreach loop for multiple arrays or accessing multiple values price,type,name in a single array ? Commented Mar 15, 2015 at 8:07
  • So you want to loop through all 3 arrays an just print them? Commented Mar 15, 2015 at 9:09
  • @Rizier123 that is the solution found. Commented Mar 15, 2015 at 9:16
  • @em0tic0n If you found your own solution please don't put it in your question make an answer Commented Mar 15, 2015 at 9:23

2 Answers 2

3

This should work for you:

(Here I just go through all 3 arrays with array_map() an print them in the structure you want)

<?php

    array_map(function($v1, $v2, $v3){
        echo "<div>";
            echo "<p>$v1</p>";
            echo "<p>$v2</p>";
            echo "<p>$v3</p>";
        echo "</div>";
    }, $boardType, $hotelPrice, $hotelName);

?>

Example input/output:

$boardType = [1,2,3];
$hotelPrice = [4,5,6];
$hotelName = [7,8,9];

<div>
    <p>1</p>
    <p>4</p>
    <p>7</p>
</div>
<div>
    <p>2</p>
    <p>5</p>
    <p>8</p>
</div>
<div>
    <p>3</p>
    <p>6</p>
    <p>9</p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

If all arrays have exactly the same size you could use each to iterate through the other arrays at the same time as $hotelName:

<?php foreach ($hotelName as $index => $name):?>
    $price = each($hotelPrice);
    $boardType = each($boardType);
<div>
<p><?php echo $name;?></p>
</div>
<?php endforeach?>

However, in that case it would probably being better to have just a single array containing all the data.

2 Comments

It was a little unclear question I think, so it was almost a trap. (Aus Berlin also, dann solltest du mich ja verstehen :D)
@Rizier123 Die array_map() Lösung ist super! +1 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.