Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $k => $v in foreach($ex as $k=>$v) mean? [duplicate]

Tags:

foreach

php

Possible Duplicates:
What does “=>” mean in PHP?

What does $k => $v mean?

like image 694
tonoslfx Avatar asked Nov 27 '22 22:11

tonoslfx


2 Answers

It means that for every key-value pair in the traversable variable $ex, the key gets assigned to $k and value to $v. In other words:

$ex = array("1" => "one","2" => "two", "3" => "three");
foreach($ex as $k=>$v) {
   echo "$k : $v \n";
}

outputs:

1 : one
2 : two
3 : three
like image 184
Saul Avatar answered Dec 10 '22 04:12

Saul


$k is the index number where the $v value is stored in an array. $k can be the associative index of an array:

$array['name'] = 'shakti';
$array['age'] = '24';

foreach ($array as $k=>$v)
{
    $k points to the 'name' on first iteration and in the second iteration it points to age.
    $v points to 'shakti' on first iteration and in the second iteration it will be 24.
}
like image 41
Shakti Singh Avatar answered Dec 10 '22 04:12

Shakti Singh