+ 2
can anyone give me an example about second situation //$key=>$value
i dont understanding
9 Antworten
+ 5
// You can get current element's key. Example:
<?php
$names = array("John", "David", "Amy");
foreach ($names as $key => $value) {
echo "value is ".$value.'<br />';
echo "key is ".$key.'<br />';
}
?>
// output
value is John
key is 0
value is David
key is 1
value is Amy
key is 2
+ 2
study arrays
+ 2
$key would be the index of $value.
e.g:
$array = array("value1","value2");
foreach($array as $key=>$value) {
echo $key."--".$value;
}
output:
0--value1
1--value2
+ 1
Alvaro Rojas Sorry
But there is a slight mistake by you in your code.
You cannot use "array" as a variable $array.
I think it is reserved word. Isn't it?
+ 1
hieu
0
You can get current element's key. Example:
<?php
$names = array("John", "David", "Amy");
foreach ($names as $key => $value) {
echo $key.'<br />';
}
?>
0
// Multidimensional associative array for learning purposes
$multiarr = array(
"Fruits" => array("Apples", "Pears", "Bananas", "Oranges"),
"Cars" => array("BMW", "VW", "Toyota", "Audi"),
"Cities" => array("New York", "London", "Toronto", "Sydney")
);
// Looping through $multiarr which is a multidimensional array
foreach($multiarr as $key => $subarrays) {
// !!Printing $subarrays will produce error since $subarrays are arrays and not strings!!
// We are printing the keys to use as headers. Keys can be associative or numeric
echo "<h3>" . $key . "</h3>";
// Now we need to loop through arrays inside $multiarr to print out data.
// No need for $key unless you need specific numeric info for further code
foreach ($subarrays as $data) {
echo $data . "<br>";
}
}
/* OUTPUT:
Fruits:
Apples
Pears
Bananas
Oranges
Cars
BMW
VW
Toyota
Audi
Cities
New York
London
Toronto
Sydney
*/
- 1
associative arrays
- 1
if you use associative array eg array('name'=>30)