Please explain what is the meaning of
foreach ($toplist['children'] as $subkey => $subname)
and where the children come from. I'm confused.
Basically $toplist is an array of values. One of those values has been called 'children'.
In this case, the value at position 'children' is itself an array.
Your line of code is telling the computer to loop over each of the values inside the 'children' array and extract the key and value.
$subkey is the key, $subname is the name.
In other words, $toplist['children'][$subkey] == $subvalue
The other elements are coming from the $toplist['children'] array which you got to figure out where it is coming from since you have not put in all the needed code for the question. See this about foreach machenism to learn more about it.
his simply gives an easy way to
iterate over arrays. foreach works
only on arrays, and will issue an
error when you try to use it on a
variable with a different data type or
an uninitialized variable.
php.net
Related
I have an array (or associative array), with keys and values.
Then, when trying to read one of the keys, which IS in the array, I get an "undefined offset" notice.
I have two examples where it happened. One was "exploding" a string like "AAA|BBB|CCC", using | as the separator, then trying to read the resulting array at position 1.
var_dump() correctly shows an array having offsets 0 to 2, with the correct values. But I still get the notice.
Another example is I get an array (from an AJAX call, I json_decode it, etc), then I typed the following code:
foreach (array_keys($myDecodedArray) as $k) {
$value = $myDecodedArray[$k];
someOtherCode();
}
I had that damn notice appear when trying to read $myDecodedArray[$k], although php itself had just told me the key existed !
So, I solved that last case by going
foreach ($myDecodedArray as $k => $value) {
someOtherCode();
}
but still, this is extremely annoying, and makes no sense to me.
Any of you run into that problem before?
Do you have any information about what could cause that?
[EDIT]
Rahul Meshram's suggestion (which I upvoted in the comments) solved my second problem case.
However, the first case still happens (exploding a string into an array, then trying to access that array's values by their numeric keys).
The keys ARE numeric (gettype returns 'integer', var_dump on that key shows an integer too, with the right value), but trying to access $explodedArray[1] still results in that notice being displayed, despite $explodedArray having keys 0, 1, and 2, with associated values.
I'm using a framework at work that I'm slightly unfamiliar with and trying to access elements of an object that are stored within an array called $items. I've tried die(print_r($items[0])) to try to get the first element but it says 0 is an undefined index. Here is the result of print_r($items):
Any help is much appreciated. If you have any questions I'll gladly answer because I know this is a bit vague. I think it would take up way too much space to explain how this framework actually works.
I figured out that the first element is 2 and not 0, but I'm still unable to access any of the elements within the object. When I tried print_r($items[2]->fields) it didn't return anything, just a blank page.
I think this is what you want:
$item = current($items);
foreach ($item->fields as $key => $val) {
echo "$key => $val\n";
}
Update:
It seems like you cannot get $item->fields since it is a protected property of Dase_DBO_Project object:
[fields:protected] => Array
I don't see any element with index 0 in your array, only keys 5, 4, 3 and 2. To get the first item from array use current($items) or reset($items).
Your array listed here does not have an index of 0 (For more help look here: http://php.net/manual/en/language.types.array.php)
Rather than attempting to access each item with the index. Why don't you use a foreach?
foreach($items as $item)
{
//Do what you want with each object here
var_dump($item);
}
This will allow you to access each object without using the index. For more information using foreach take a look here: http://us3.php.net/manual/en/control-structures.foreach.php
Cheers!
When I send over post data I do a print_r($_POST); and I get something like this...
Array ( [gp1] => 9 )
Is there a way to get the "gp1", the name sent over as a value? I tried doing.
echo key($_POST["gp1"]);
But no luck there, I figured it would echo gp1. Is there a way to do this?
you need
print_r(array_keys($_POST));
check this for more details http://php.net/manual/en/function.array-keys.php
You could use foreach to see each key-value pair, or use array_keys to get a list of all keys.
foreach ($_POST as $key => $value) {
// Do whatever
}
Well, if you can write $_POST["gp1"] you already have the key anyway ;)
key() works differently, it takes an array as argument:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
So if you have not done anything with the array (no traversing), key($_POST) would give you the key of the first element of the array.
Maybe you want a foreach loop?
foreach($_POST as $key => $value) {
}
There are other methods to retrieve keys as to well. It depends on what you want to do.
I was wondering if foreach() works when the array looks like this:
arr_name[eggs] = something
arr_name[pencil] = something else
Will foreach work if run as:
foreach(arr_name as $key => $value)
for they keys that have a non-numerical value ?
Yes, foreach supports any kind of key. In your case, $key will be a string, 'eggs' and 'pencil' respectively for each item. In fact, foreach was intended for use with arrays that have non-numerical keys which you can't easily iterate using for.
Yes, PHP has no real distinction between arrays with numeric vs non-numeric keys. They're all simply arrays as far as PHP is concerned.
Yes the explanation given by BoltClock is right & i would suggest you to manually try too. You have missed $before array name in the foreach statement
foreach($arr_name as $key=>$value)
echo $value
?>
Could some one explain me this while loop?
while (list($key, $value) = each($HTTP_GET_VARS)) {
$get_url .= $key . '=' . $value . '&';
}
I know its silly but many times silly things makes huge difference....
$HTTP_GET_VARS is a deprecated array that contains the parameters passed in the querystring. each() is a function that iterates through an array and returns an array consisting of the key and value of the "current" element of the array. list() is a language construct that explodes an array assigned to it into the variables passed to it.
When the end of the array is reached, each() returns a false value, causing the loop to exit.
The each() function returns the current key and value for the given array, and then moves the array pointer (the current item) forward by one.
Therefore, calling it multiple times is a way to iterate through the items in the array in order, and when you reach the end, each() just stops returning a value.
The list() is not a function but a language construct; it's a shortcut for setting multiple variables at once. In the example posted it sets $key to the first value in the array returned by each() (the current key) and $value to the second (the current value).
There's a number of problems with that code snippet.
You should reset the array pointer before you use each() like this, because you shouldn't assume that the array pointer is at the start by the time this code executes.
The values it is concatenating into a query string should be escaped (eg. by urlencode()).
It's also leaving a separating '&' character at the end of the query string unnecessarily.
$HTTP_GET_VARS is a deprecated feature of PHP; it should be replaced with $_GET.
Iterating over an array with foreach () is cleaner and easier to read than while, list, each like this, and may be faster too.
each returns an array containing the current key and value, as you iterate through an array. list lets you unpack an array into multiple variables. I find the foreach construct much more clear.
foreach ($some_array as $key => $value)
{
...
}
As noted by Ignacio, HTTP_GET_VARS is deprecated. You can use $_GET instead.
The loop goes through each of the pairs of HTTP GET parameters in the array $HTTP_GET_VARS, assigning the sides of the pair to two variables $key and $value in that order.
The assignment 'returns' its value, hence, at the end of the array, each() will return false, which despite the assignment will cause the while condition to abort.
Inside the loop, each of $key and $value are appended to the string $get_url with some formatting.