Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

I don't understand the foreach loop in PHP

I have two arrays. I then create a third empty array, which gets populated with the details of the first two. I have it working, but I don't understand why

<?php

$map = array(

    'Title',
    'Name',
    'Lastname',

);

$data = array(
    'Mr',
    'Kristian',
    'Woods',
);


$row = array();
      if (is_array($map) && count($map) > 0 && is_array($data) && count($map) > 0) {
        foreach ($map as $key => $field) {
          $row[$field] = $data[$key]; // I'm confused at this line
        }
      }
?>

So, are you creating a key for '$row' on the first pass through the loop. And that key equals 'Title' on the first pass. 'Name' on the second pass. Then 'Lastname' on the third?

I'm confused at:

<?php
    $row[$field] = $data[$key];
?>

$data[$key] - I thought would be 0, 1, 2 - as you go through the array. But, no, it comes up with 'Mr', 'Kristian', 'Woods' - I thought $key was the index value of that array....????

1 Answer

John Awoyele
John Awoyele
36,212 Points

So $key = 0,1,2 as the loop iterates (goes around),

$data[0] = 'Mr' $data[1] = 'Kristian'

e.t.c.

print_r($data);
Array
(
    [0] => Mr
    [1] => Kristian
    [2] => Woods
)