View Full Version : Resolved php
ggalan
04-30-2011, 05:49 PM
what's the difference between these 2 symbols
-> (reference to a method?)
=>
djr33
04-30-2011, 07:24 PM
<?php
$myclass->mymethod();
$myclass->myvar;
$array = (
'key1'=>'value1',
'key2'=>'value2'
);
foreach ($array as $key=>$value) { /*...*/ }
?>
-> is used to access things within a class.
=> is used for arrays to relate a key to a value
ggalan
05-01-2011, 02:47 AM
thank you. in your example, how would you use the variable $key ?
djr33
05-01-2011, 03:34 AM
$array = (
'key1'=>'value1',
'key2'=>'value2'
);
foreach ($array as $key=>$value) {
echo $key.'=>'.$value.'<br/>';
}
Assuming your keys and values are all strings (or integers), that will display them in pairs, one per line.
A foreach loop is a special kind of loop that goes through each entry in an array and gives you access to that value as well as it's corresponding key. This can often be useful. Sometimes you don't need the key, though, so you may want to use the second, alternative, method posted below:
//alternative:
foreach ($array as $value) {
echo $value.'<br/>';
}
?>
Note that the key is required if during the loop you want to alter the original value stored in the array.
//add 1 to each entry in an array:
foreach ($array as $key=>$value) {
echo $array[$key] = $value+1;
}
?>
(of course that assumes the values are all numbers-- the keys can be any valid key you'd like)
ggalan
05-01-2011, 07:18 PM
so the key is an extra variable to alter while preserving the original array value?
djr33
05-01-2011, 07:24 PM
A 'key' is the term used for the named index in an array. The 'value' is the value associated with that key. These are standard terms. More generally, you should think of an array as a set of pairs, and that for each pair the first entry is called a key and the second entry is called a value.
You can do anything you want with them. But often, yes, you will use the key to refer back to the original entry in the array.
Note that $key and $value will be different with each rotation through the loop, but afterward they will still be available (with values from the last rotation) just like any other variable.
Also, there is no reason that you must name them "key" and "value". I'm just doing that for clarity. Here's an example where that is not the case:
$ages = array(
'John' => 44,
'Mary' => 52,
'Bill' => 37
);
foreach($ages as $name=>$age) {
echo $name.' is '.$age.' years old.<br/>';
}
//or, if for some reason you want to discuss next year:
foreach($ages as $name=>$age) {
$ages[$name] = $age+1;
}
foreach($ages as $name=>$age) {
echo $name.' will be '.$age.' years old.<br/>';
}
//Note: you could easily combine the two loops above into a single loop,
//but I'm separating them specifically to show you what foreach loops can do.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.