tags:

views:

163

answers:

3

I don't understand the => part.

foreach ($_POST[‘tasks’] as $task_id => $v) {

What does it do in a foreach loop?

+2  A: 

In PHP, all arrays are associative arrays. For each key and value pair in the array, the key is assigned to $task_id and the value is assigned to $v. If you don't specify another key, the key is a 0-based integer index, however it can be anything you want to, as long as the key is only used once (trying to reuse it will mean overwriting the old value with a new value).

Thomas Owens
I'm not sure that your understanding of the syntax is correct... ?
harto
It is. $task_id is the key, and $v is the value mapped to that key. An array in PHP is an associative array.
Thomas Owens
Although yes, my wording should be improved. Let me do that.
Thomas Owens
OK. The wording of your answer suggests that $task_id and $v have the same value.
harto
Your wording is terrible.
Mark
I think that's significantly better.
Thomas Owens
+12  A: 

A foreach loops goes through each item in the array, much like a for loop. In this instance, the $task_id is the key and the $v is the value. For instance:

$arr = array('foo1' => 'bar1', 'foo2' => 'bar2');
foreach ($arr as $key => $value)
{
  echo $key; // Outputs "foo1" the first time around and "foo2" the second.
  echo $value; // Outputs "bar1" the first time around and" bar2" the second.
}

If no keys are specified, like in the following example, it uses the default index keys like so:

$arr = array('apple', 'banana', 'grape');
foreach ($arr as $i => $fruit)
{
  echo $i; // Echos 0 the first time around, 1 the second, and 2 the third.
  echo $fruit;
}

// Which is equivalent to:
for ($i = 0; $i < count($arr); $i++)
{
  echo $i;
  echo $arr[$i];
}
James Skidmore
looks more like a map than an array.
Pablo Fernandez
@Pablo: PHP 'arrays' are very useful little things, and can be used as a map or an array.
Thanatos
Actually, I think it's better to say that all PHP arrays are associative arrays. By default, the key is a 0-based integer value, but you can make it anything you want to.
Thomas Owens
+2  A: 

From the context, it looks like $_POST['tasks'] is an array of some sort. That foreach() takes each key/value pair in that array, and places the key in $task_id and the value in $v. For instance, if you had:

$a['q'] = "Hi";
$a[4] = "BLAH";

In the first iteration, $task_id would be 'q', and $v would be "Hi". In the second iteration, $task_id would be 4, and $v would be "BLAH".

Thanatos