em0tic0n
em0tic0n

Reputation: 290

PHP Foreach with two or more arrays

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?>

Upvotes: 1

Views: 89

Answers (2)

Rizier123
Rizier123

Reputation: 59681

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>

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 157947

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.

Upvotes: 1

Related Questions