Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using foreach and for loop in PHP

I have 2 kinds of ARRAYS

<?php
    $array1 = array("Car", "House", "Money");
    $array2 = array("John", "Peter", "Mary");

foreach ($array1 as $a1) {
    for($i = 0; $i < count($array2); $i++) {
        if ($a1 === end($array1 )) {
          echo $array2[$i].' has '.$a1.'.<br>';
        }
        else {
          echo $array2[$i].' has '.$a1.',<br>';
        }
    }
}
?>

But the output is like this

John has Car,
Peter has Car,
Mary has Car,
John has House,
Peter has House,
Mary has House,
John has Money.
Peter has Money.
Mary has Money.

What I want is like this

John has Car,
Peter has House, 
Mary has Money.

is there any other way?

except for calling the specific value of an array like this

$array1[0]."has ".$array2[0].",<br>"
$array1[1]." has ".$array2[1].",<br>" 
$array1[2]." has ".$array2[2].".<br>"

if I need to use "break;" where should I put it?

TIA

like image 329
Jerick Arcega Avatar asked Aug 11 '26 17:08

Jerick Arcega


2 Answers

Please check my answer helpful for you.

<?php
    $array1 = array("Car", "House", "Money");
    $array2 = array("John", "Peter", "Mary");

for($i = 0; $i < count($array2); $i++) {

          echo $array2[$i].' has '.$array1[$i].'.<br>';

    }

?>

and output as below:

John has Car. Peter has House. Mary has Money.

like image 172
Subhash Patel Avatar answered Aug 14 '26 12:08

Subhash Patel


You don't need to loop twice. You can simply iterate over the list of people and use the given key to access the corresponding object:

$objects = ['Car', 'House', 'Money'];
$people = ['John', 'Peter', 'Mary'];

foreach ($people as $i => $person) {
  echo $i > 1 ? ' and ' : '', $person, ' has ', $objects[$i];
}

Demo: https://3v4l.org/Fa45t

Note that this assumes the two arrays have the same size. You can use array_key_exists (or isset in this case) to make sure, otherwise.

Updated after your edit. This handles the case where there are more people than objects:

$objects = ['Car', 'House', 'Money'];
$people = ['John', 'Peter', 'Mary', 'Paul'];

foreach ($people as $i => $person) {
  if (!array_key_exists($i, $objects)) {
    break;
  }
  echo ($i > 0 ? ',<br>' : ''), $person, ' has ', $objects[$i];
}

Demo: https://3v4l.org/Hd3e0

like image 24
Jeto Avatar answered Aug 14 '26 12:08

Jeto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!