Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Syntax

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Syntax

Postby Sunny » Sat Jan 12, 2013 12:49 am

Hi

What does this mean

foreach ($beatles as $key => $beatle)
{
echo "<b>$key:</b> $beatle<br>";
}

$beatles is array

Thanks
Sunny
New php-forum User
New php-forum User
 
Posts: 23
Joined: Wed Nov 30, 2011 6:51 am

Re: Syntax

Postby simplypixie » Sun Jan 13, 2013 12:25 am

Every element in an array consists of a key => value pair. Depending on how the array has been created this will either be a numeric key based on the position of the element in the array (starting at zero) or a name.

For example:
Code: Select all
<?php

$example_array1 = array('Apple','Potato','Dog');

print_r($example_array1);
// Using print_r will show you the array items with a numeric index

Array
(
    [0] => Apple
    [1] => Potato
    [2] => Dog
)

$example_array2 = array('fruit' => 'Apple', 'vegetable' => 'Potato', 'animal' => 'Dog');

print_r($example_array2);
// Using print_r will show you the array items with a named index

Array
(
    [fruit] => Apple
    [vegetable] => Potato
    [animal] => Dog
)
?>

In each case the $key is the numeric or named index and the $value is the value of each item.

To go through elements in an array you use for or foreach, so in your example it is saying for each element in the array $beatles extract each element's key and value (this is where the 'as' comes into play) and echo out the data.

It might make more sense to you if we change $beatle to $value
Code: Select all
foreach ($beatles as $key => $value) // For each element in the $beatles array, extract the $key and $value
{
echo "<b>$key:</b> $value<br>"; // echo the $key (numeric or named) and that key's value
}


I hope this helps and hasn't confused you more :)
User avatar
simplypixie
php-forum Active User
php-forum Active User
 
Posts: 300
Joined: Sun Dec 11, 2011 12:51 am
Location: Shrewsbury, Shropshire


Return to PHP coding => General

Who is online

Users browsing this forum: Google [Bot], Majestic-12 [Bot] and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.