Undefined offset in array - But I know it's in there - php

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.

Related

Push or Merge data into existing Array

When working with existing code, it takes one array and places it into another in the fashion shown below.
I believe the empty brackets are the same thing as simply pushing it and appending it to the first available index.
$g['DATA'][] = $p;
After this is done, I have my own array that I would like to append to this as well. I tried using array_merge() with $g['DATA'][]as a parameter, but this is invalid for obvious reasons.
My only thought is to create a foreach loop counter so I can figure out the actual index it created, however I have to assume there is some cleaner way to do this?
Just simply use the count() of your $g["DATA"] array as index and then you can merge it like this:
$g['DATA'][count($g["DATA"])-1] = array_merge($g['DATA'][count($g["DATA"])-1], $ownArray);
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
// -1 Because an array is based index 0 -> means count() - 1 = last key

Getting notice "Array to string conversion" when using call_user_func_array()

I wanted to check for matching values in multiple arrays, so I made a multi-dimensional array by pushing them into $array and then wrote this line of code:
$result = call_user_func_array('array_intersect', $array);
I am getting the result I want, but I am always getting this notice on that particular line of code:
Notice: Array to string conversion
Wondering what's causing this. Hope someone can enlighten me.
Your arrays (the first-level items inside $array) themselves contain arrays. This is unsupported by array_intersect, because it treats the array items as strings for purposes of determining equality:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2.
In words: when the string representation is the same.
I can't say definitely without knowing what exactly you are trying to do, but a possible solution is to use array_uintersect instead which will allow you to specify in code how to compare items without necessarily casting them to string.

Finding the length of an associative array encoded by PHP

I have a multidiminsional array that I have created in php that is passed back to a jQuery script. I need to iterate through this array and process the data.
In Firebug I can see that the data is located at data.data.items. I've tried finding the length of the array using data.data.items.length, but it comes back as undefined. Interestingly, this worked prior to my php portion working correctly when it passed back an array of 8 empty items. Now that it's populated (and the indexes are strings), length doesn't work. There is also an object in each of the items. What's breaking this?
An Array in JavaScript is an object nonetheless. When setting values using strings (or anything that isn't an integer), you are actually setting a property of the object (you are actually doing this when setting it with integer keys as well, but it's handled slightly differently).
To the issue of its sudden breakage after using strings as keys, I would expect that PHP realizes when you have an honest-to-goodness array versus an associative array, thus it sends arrays (surrounded by []) when all keys are integers, and objects (surrounded by {}) otherwise. I believe in the string-keyed case, PHP is generating objects, and thus .length becomes undefined (rather than 0 as in an empty array).
To answer your question, there is a simple way to count the "length" of this data:
var i = 0;
for (var item in data.data.items) {
i++;
}
Which will iterate through each property of data.data.items and count them. Note that if you (or any library you include) adds a property to the Object prototype, this will not produce expected results. This is fairly uncommon, but you must be aware of it when using for..in.
You can address this by using the method Nagh suggested, which ignores properties not defined on that particular object:
var i = 0;
for (var item in data.data.items) {
if(data.data.items.hasOwnProperty(item)) {
i++;
}
}
You can always use "foreach" kind of loop. In this case, you don't need to know what array length is there or even is it array or not, since you can iterate over object properties aswell.
As Joe already has pointed, javascript doesn't have associative arrays and when you trying to use one - you end up with object with properties. However, if u sure, that only properties this object got - is your array you can use code like that:
for (i in arr) {
if (arr.hasOwnProperty(i)) {
//do something with arr[i]
}
}
However if you really need an array, consider using integer as an array index.

I Don't Understand This Array Syntax

I don't understand this array accessing syntax:
$target[$segs[count($segs)]]
Is it really possible to use variables as multidimensional array keys?
That might result in an error, if $segs is a numerical array with continuous indices only.
Meaning, it would fail for:
array("foo","bar");
but work for
array("foo", 2=>"bar");
Assuming now, that we deal with the first case, then this would work:
$target[$segs[count($segs) - 1]]
First, count($segs) - 1 will be evaluated and return a number. In this case the last index of $segs (provided it is a numerical array).
$segs[count($segs) - 1] will therefore return the last element in $segs. And whatever that value is, will be used as index for $target[...].
To sum up: It is nested array indexing and evaluated inside out.
See it in action.
Whether or not such a method is necessary depends on the problem you are trying to solve. If you don't know where you would use such nested, variable array indexing then you probably don't need it.
That syntax is fine, provided $segs is an array. It's worth noting, though, that if you're using a numerically indexed array for $segs, calling count($segs) is a non-existent key because indexing starts at zero.

multidimensional array

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

Categories