makapaka
makapaka

Reputation: 179

Looping through 2 matching arrays in PHP

I have 2 arrays, they are the same size, and each element corresponds to the same item in each array, ie, arrays look like

array1 => 'name', 'description', 'value' 
array2 => 'fred', 'manager', '100000'

So its basically a 2D array but they are separate due to the way they are built.

How do I iterate through them together so that I can join them like

name=fred, description=manager, 

all in the same loop ?

EDIT Just realised i may have 3 arrays, array1, array2, array3, I assume that eliminates array_combine as an option ?

Upvotes: 0

Views: 42

Answers (3)

Mramaa
Mramaa

Reputation: 390

for($x=0;$x<count($array1);$x++) {
$element1 = $array1[$x];
$element2 = $array2[$x];
//Now you can use these elements
}

or use array_combine()

$array3 = array_combine($array1,$array2);
for($x-0;$x<count($array3);$x++){
$element2 = $array3[$x];
$element1 = key($array[$x]);
}

or

$array3 = array_combine($array1,$array2);
foreach ($array3 as $element1 => $element2){
//Do what you want
}

http://php.net/manual/en/function.array-combine.php

What you prefer find/easiest...

Upvotes: 1

JimboSlice
JimboSlice

Reputation: 692

$array3 = array_combine($array1,$array2);

Upvotes: 0

Ziumin
Ziumin

Reputation: 4860

I suggest you to use array_combine PHP function.

Upvotes: 1

Related Questions