0

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 ) )
1
  • 1
    That array is already chunked. Look at array_column if you have php 5.5 Commented Feb 14, 2015 at 0:57

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.