CWright
CWright

Reputation: 2098

parsing arrays using foreach

I have an array in the form

$array = array(
    name => array (
        [0] => peter,
        [1] => george,
        [2] => sarah
    ),
    age => array(
        [0] =>1,
        [1] =>2,
        [2] =>3
    )
)

I want to parse it out into a table but when I use a foreach loop I can't seem to get it to output properly.

If I use

foreach($array[name] as $name){
    foreach($array[age] as $age{

        echo $name.$age;
    }
}

sort of thing then it just outputs the name with each age and then moves to the next name and then does all 3 ages and then the final age..

I want:

Name1 Age1 Name2 Age2 Name3 Age3

Upvotes: 0

Views: 229

Answers (6)

Marc B
Marc B

Reputation: 360572

foreach (array_keys($array['name']) as $key) {
    echo $array['name'][$key] . $array['age'][$key];
}

Basically, get the sub-array keys from one of your "main" arrays, then use that key inside the loop to extract whatever data you need from the two child arrays.

You can find more detailed information on array_keys here on official documentation.

Upvotes: 4

RafaSashi
RafaSashi

Reputation: 17205

Use while insted:

$i=0;
$len=count($array['name']);
while($i<$len){
   echo $array['name'][$i].$array['age'][$i];
   ++$i;
}

Use pre-calculations, set the maximum value for your loop before and not in the loop.

See the follwing article for micro optimization tips http://labs.phurix.net/posts/50-php-optimisation-tips-revisited

Upvotes: 0

footy
footy

Reputation: 5911

Here is the code to your question:

<?php
$array = array(
"name" => array (
0 => "peter",
1 => "george",
2 => "sarah"
),
"age" => array(
0 =>1,
1 =>2,
2 =>3
)
);
$name = $array['name'];
$age = $array['age'];


for($i=0;$i<count($name);$i++)
{
 echo $name[$i].' '.$age[$i].' ';
}
?>

Upvotes: 0

Nicklasos
Nicklasos

Reputation: 565

for ($i = 0; $i < count($array['name']); $i++) {    
   echo $array['name'][$i].$array['age'][$i];
}

Upvotes: 0

Krystian Podemski
Krystian Podemski

Reputation: 1491

$array = array(
    'name' => array(
    0 => 'peter',
    1 => 'george',
    2 => 'sarah'
    ),
    'age' => array(
    0 =>'1',
    1 =>'2',
    2 =>'3'
    )
);

foreach($array['name'] as $key => $value)
{
    echo 'Name: ' . $value . ' - Age: ' . $array['age'][$key].'<br />';
}

Edit: Oh, too late :)

Upvotes: 1

VancleiP
VancleiP

Reputation: 657

Try this:

foreach($array['name'] as $iKey => $name){

echo $name.$array['age'][$iKey];

}

Upvotes: 8

Related Questions