xylar
xylar

Reputation: 7673

Undefined offset when using array_chunk

I have the following array:

$people = array(
            array(  'name'=>'Sarah',
                    'gender'=>'F'),
            array(  'name'=>'Darren',
                    'gender'=>'M'),
            array(  'name'=>'John',
                    'gender'=>'M'),
            array(  'name'=>'Phil',
                    'gender'=>'M'),
            array(  'name'=>'Alice',
                    'gender'=>'F'),
            array(  'name'=>'Sam',
                    'gender'=>'M'),
            );

I would like to get it to display in a 2 column structure as follows:

Sarah | Darren
John | Phil
Alice | Sam

I am using array_chunk and looping through as follows:

foreach(array_chunk($people, 2, true) as $array)
{
    ?>
    <div class="left"><?php echo $array[0]['name']; ?></div>
    <div class="right"><?php echo $array[1]['name']; ?></div>
    <?php
}

The above does not work because it says: Undefined offset: 0

The value of print_r($array) is:

Array ( [0] => Array ( [name] => Sarah [gender] => F ) [1] => Array ( [name] => Darren [gender] => M ) )

Upvotes: 0

Views: 586

Answers (2)

Haring10
Haring10

Reputation: 1557

I achieved the output like this:

$count = 0;
foreach($people as $person) {
if($count % 2 == 0) {
    echo $person['name'] . ' | ';
} else {
    echo $person['name'] . '<br /><br />';
}
$count++;
}

Upvotes: 0

castis
castis

Reputation: 8223

You passed true as the 3rd arg to array_chunk(), that preserves keys.

0 doesnt exist on the 2nd loop because the next available index would be 2.

Remove the 3rd argument from array_chunk and you should have what you need.

Upvotes: 1

Related Questions