Solved

How does this foreach loop work?

Posted on 2006-06-26
19
439 Views
Last Modified: 2012-06-27
How does a foreach loop work?

My array is SESSION['cart'][] = ...
0
Comment
Question by:weikelbob
  • 6
  • 4
  • 3
  • +3
19 Comments
 
LVL 7

Accepted Solution

by:
maUru earned 100 total points
ID: 16989134
say you have an array:

$array = array('a', 'b', 'c');

foreach ($array as $val) {
echo $val;
}
outputs: abc

say you have a associative array:

$array = array('a' => 'apples', 'b' => 'bears', 'c' => 'cars);

foreach ($array as $key => $val) {
echo $key . '-' . $val . ',';
}
outputs: a-apples,b-bears,c-cars,
0
 
LVL 7

Author Comment

by:weikelbob
ID: 16989222
When do you use an associative array?
0
 
LVL 6

Assisted Solution

by:soapergem
soapergem earned 100 total points
ID: 16989369
> When do you use an associative array?

Whenever you want to. They can be very useful if you are retrieving data from a MySQL database. Here's an example:

    $result = mysql_query('SELECT item_description, item_author FROM items WHERE item_id = 1');
    if ( $row = mysql_fetch_array($result) )
    {
        $description = $row['item_description'];
        $author = $row['item_author'];
    }

It's *a lot* easier to keep track of them when you can refer to a column as $row['item_description'] rather than $row[0]. There are many, many, many other uses for them as well; that's just one example. (By the way, the function mysql_fetch_array() returns an associative array, if you haven't figured that out by now.)
0
 
LVL 7

Author Comment

by:weikelbob
ID: 16989426
I'm still unclear. Can you give me an example of an associative array that doesn't involve a database?
0
 
LVL 6

Expert Comment

by:soapergem
ID: 16989449
An associative array is no different from any other array, except that you refer to its contents using strings instead of numbers.

$numerical_array = array();
$numerical_array[0] = 'Alpha';
$numerical_array[1] = 'Beta';
$numerical_array[2] = 'Gamma';

$associative_array = array();
$associative_array['A'] = 'Alpha';
$associative_array['B'] = 'Beta';
$associative_array['C'] = 'Gamma';

It's just however you prefer to access the data. There are a lot of examples where numerical arrays are practically impossible because you, as a PHP programmer, need to keep track of each piece of data by name. There are other cases where numerical arrays are absolutely required because you need to iterate over the array or whatnot. Oh, and arrays can have both numerical and associative indeces, of course. And by the way, associative indeces are case sensitive, so $associative_array['A'] is different from $associative_array['a'].
0
 
LVL 6

Expert Comment

by:soapergem
ID: 16989457
And of course, these two commands will do exactly the same thing:

1.    echo $associative_array['Abc'];

2.    $string = 'Abc';
       echo $associative_array[$string];
0
 
LVL 49

Assisted Solution

by:Roonaan
Roonaan earned 100 total points
ID: 16989667
Bob,

In sessions and other superglobals you most of the time use associative arrays as well. In the below snippet you use assoc three times:
if($_POST['username'] == 'bob' && $_POST['password'] == 'lekeiw') {
  $_SESSION['loggedin'] = true;
}

For a shopping cart I can imagine something like this:
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'add')) {
  $_SESSION['cart'][$_POST['itemid']] = $_POST['itemcount'];
}

Then you output your cart by:

echo '<table>';
echo '<tr><th>ItemID </th><td>Number of items</td></tr>';
foreach($_SESSION['cart'] as $itemid => $itemcount) {
  echo '<tr><td>'.$itemid.'</td><td>'.$itemcount.'</td></tr>';
}
echo '</table>';

This  is a somewhat abstract example because a cart should store so much more details on the items it contains. For example:
foreach($_SESSION['cart'] as $itemid => $details) {
  echo '<tr><td>'.$itemid.'</td><td>'.$details['description'].'</td><td>'.$details['count'].'</td><td>'.$details['price'].'</tr>';
}

Hope this helps,

-r-
0
 
LVL 29

Assisted Solution

by:TeRReF
TeRReF earned 100 total points
ID: 16990299
Another important advantage of associative arrays is that if for whatever reason the order of your array changes, your code will still work. If you just use the index number, your code will break...
0
 
LVL 7

Author Comment

by:weikelbob
ID: 16990789
Thanks guys. Roonaan, I'm saving a description, a quantity, and a shipping amount for each purchased item in my sessions. I assume I should use associative arrays. What's the best way to organize this?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 49

Expert Comment

by:Roonaan
ID: 16990801
I think something like:

$_SESSION['cart']['itemid'] = array('id' => 'itemid', 'quantity' => 'number', 'description' => 'text', 'price' => 0.00, 'shipping' => 0.00);

-r-

0
 
LVL 7

Expert Comment

by:maUru
ID: 16991037
using roonaans code, you can access data by:

echo $_SESSION['cart']['id']; //echos id
echo $_SESSION['cart']['quantity']; //echos quantity
etc.

also one little typo in his code: 'quantity' => 'number' should be 'quantity' => 0
0
 
LVL 40

Assisted Solution

by:RQuadling
RQuadling earned 100 total points
ID: 16991038
One thing to watch out when using mutliple dimensional arrays is that the outer most array normally represents a row.

This is great, you normally want to access 1 row at a time.

But when it comes to sorting, you sort by columns.

So, say you have the following array from a DB (or anywhere).

$an_array = array
      (
      0 => array
            (
            'id' => 1234,
            'quantity' => 12,
            'description' => 'Cheap book',
            'price' => 9.99,
            'shipping' => 2.00,
            ),
      1 => array
            (
            'id' => 4321,
            'quantity' => 21,
            'description' => 'Another Cheap book',
            'price' => 19.99,
            'shipping' => 1.40,
            ),
      );

Now you want to sort this array by description. You would have to extract the descriptions into an array to sort them.

But if the array was such ...

$an_array = array
      (
      'id' => array
            (
            0 => 1234,
            1 => 4321,
            ),
      'quantity' => array
            (
            0 => 12,
            1 => 21,
            ),
      'description' => array
            (
            0 => 'Cheap book',
            1 => 'Another Cheap book',
            ),
      'price' => array
            (
            0 => 9.99,
            1 => 19.99,
            ),
      'shipping' => array
            (
            0 => 2.00,
            1 => 1.40,
            ),
      );

You can now use array_multisort()..

print_r($an_array);
array_multisort($an_array['description'], $an_array['id'], $an_array['quantity'], $an_array['price'], $an_array['shipping']);
print_r($an_array);


returns ...

Array
(
    [id] => Array
        (
            [0] => 1234
            [1] => 4321
        )

    [quantity] => Array
        (
            [0] => 12
            [1] => 21
        )

    [description] => Array
        (
            [0] => Cheap book
            [1] => Another Cheap book
        )

    [price] => Array
        (
            [0] => 9.99
            [1] => 19.99
        )

    [shipping] => Array
        (
            [0] => 2
            [1] => 1.4
        )

)
Array
(
    [id] => Array
        (
            [0] => 4321
            [1] => 1234
        )

    [quantity] => Array
        (
            [0] => 21
            [1] => 12
        )

    [description] => Array
        (
            [0] => Another Cheap book
            [1] => Cheap book
        )

    [price] => Array
        (
            [0] => 19.99
            [1] => 9.99
        )

    [shipping] => Array
        (
            [0] => 1.4
            [1] => 2
        )
)

As you can see, the books and their data are now sorted by their descriptions.

You would need to include all the arrays in the array_multisort.

0
 
LVL 49

Expert Comment

by:Roonaan
ID: 16991062
For sorting multidimensional arrays I often use a class:

<?php


class columnSorter {
  var $column = '';
  function columnSorter($column) {
    $this->column = $column;
  }
  function sort($a, $b) {
    $a = $a[$this->column];
    $b = $b[$this->column];
    if($a == $b) return 0;
    return $a > $b ? 1 : -1;
  }
}

$array[] = array('a' => 1, 'b' => 2, 'c' => 8);
$array[] = array('a' => 2, 'b' => 1, 'c' => 7);
$array[] = array('a' => 3, 'b' => 0, 'c' => 6);
$array[] = array('a' => 4, 'b' => 1, 'c' => 5);
$array[] = array('a' => 5, 'b' => 2, 'c' => 4);
$array[] = array('a' => 6, 'b' => 1, 'c' => 3);
$array[] = array('a' => 7, 'b' => 0, 'c' => 2);
$array[] = array('a' => 8, 'b' => 1, 'c' => 1);

$sort = new columnSorter('a');
usort($array, array($sort, 'sort'));
echo '<pre>'.var_export($array, true).'</pre>';

-r-
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 16991071
Having said that ...

<?php
$an_array = array
      (
      0 => array
            (
            'id' => 1234,
            'quantity' => 12,
            'description' => 'Cheap book',
            'price' => 9.99,
            'shipping' => 2.00,
            ),
      1 => array
            (
            'id' => 4321,
            'quantity' => 21,
            'description' => 'Another Cheap book',
            'price' => 19.99,
            'shipping' => 1.40,
            ),
      );

$a_sort = array();
foreach($an_array as $i_key => $a_data)
      {
      $a_sort[$i_key] = $a_data['description'];
      }
print_r($an_array);
array_multisort($a_sort, $an_array);
print_r($an_array);
?>

produces ...

Array
(
    [0] => Array
        (
            [id] => 1234
            [quantity] => 12
            [description] => Cheap book
            [price] => 9.99
            [shipping] => 2
        )

    [1] => Array
        (
            [id] => 4321
            [quantity] => 21
            [description] => Another Cheap book
            [price] => 19.99
            [shipping] => 1.4
        )

)
Array
(
    [0] => Array
        (
            [id] => 4321
            [quantity] => 21
            [description] => Another Cheap book
            [price] => 19.99
            [shipping] => 1.4
        )

    [1] => Array
        (
            [id] => 1234
            [quantity] => 12
            [description] => Cheap book
            [price] => 9.99
            [shipping] => 2
        )

)

Some concept but requires the extraction of the keys to sort by. Which is probably a lot easier to deal with if your HTML page has sort asc/desc buttons on columns.

You can add descending sort to the array_multisort()

array_multisort($a_sort, $an_array, SORT_DESC);

or ...

<?php
$an_array = array
      (
      0 => array
            (
            'id' => 1234,
            'quantity' => 12,
            'description' => 'Cheap book',
            'price' => 9.99,
            'shipping' => 2.00,
            ),
      1 => array
            (
            'id' => 4321,
            'quantity' => 21,
            'description' => 'Another Cheap book',
            'price' => 19.99,
            'shipping' => 1.40,
            ),
      );


$i_sort_order = SORT_ASC;
if (isset($_GET['orderby']) && in_array($_GET['orderby'], array(SORT_ASC, SORT_DESC)))
      {
      $i_sort_order = intval($_GET['orderby']);
      }

$a_sort = array();
if (isset($_GET['sorton']))
      {
      foreach($an_array as $i_key => $a_data)
            {
            if (isset($a_data[$_GET['sorton']]))
                  {
                  $a_sort[$i_key] = $a_data['description'];
                  }
            else
                  {
                  $a_sort[$i_key] = NULL;
                  }
            }
      }
print_r($an_array);
array_multisort($a_sort, $an_array, $i_sort_order);
print_r($an_array);
?>

sort of thing.

Ok. Way too much information!
0
 
LVL 7

Author Comment

by:weikelbob
ID: 17003825
Wow!, I really appreciate this detailed information. This area is my weakest, it just doesn't register like the rest of PHP does for me. Are there any simple tutorials that I could follow up with to help get this stuff sunk in?

Again, I really appreciate this.

Bob
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17007836
The trouble with self taught people like me is I don't use tutorials. I use other peoples code to learn from.

Tutorials are always out of context for me.
0
 
LVL 7

Author Comment

by:weikelbob
ID: 17014083
interesting....
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 17016168
I would take a look at the PHP Manual. It is the only PHP reference book I use.
0
 
LVL 7

Author Comment

by:weikelbob
ID: 17096341
Wow, I'm going to bookmark this one. It's one of the areas of php that I'm slow with.

Thanks guys.

Bob
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now