• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

How does this foreach loop work?

How does a foreach loop work?

My array is SESSION['cart'][] = ...
0
weikelbob
Asked:
weikelbob
  • 6
  • 4
  • 3
  • +3
5 Solutions
 
maUruCommented:
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
 
weikelbobAuthor Commented:
When do you use an associative array?
0
 
soapergemCommented:
> 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
weikelbobAuthor Commented:
I'm still unclear. Can you give me an example of an associative array that doesn't involve a database?
0
 
soapergemCommented:
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
 
soapergemCommented:
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
 
RoonaanCommented:
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
 
TeRReFCommented:
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
 
weikelbobAuthor Commented:
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
 
RoonaanCommented:
I think something like:

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

-r-

0
 
maUruCommented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
RoonaanCommented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
weikelbobAuthor Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
weikelbobAuthor Commented:
interesting....
0
 
Richard QuadlingSenior Software DeveloperCommented:
I would take a look at the PHP Manual. It is the only PHP reference book I use.
0
 
weikelbobAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 6
  • 4
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now