PHP associative array index undefined - php

Without looping a set of array keys acquired via array_keys($array), how else can I select the key of an array such that $array["key"] where "key" associates to a second subsequent array -- PHP otherwise outputs a notice stating that "key" is undefined.
Any help is sincerely appreciated.

I think you're looking for isset(), for example if( isset($array['key'])) ...

isset() works for variables, but the error your likely getting is for an undefined key/index. You'll want to try array_key_exists() before trying to use the key (and based on the results, either use or create the key).
http://www.php.net/manual/en/function.array-key-exists.php

Related

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

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.

Laravel, getting specific array index from session

Currently, I'm dumping an array that is held within my laravel session, which successfully dumps the array:
<?php dd(Session::get('Tokens'));?>
This dumps an array with three elements, each with its own index
array(
"userToken":"value",
"secondToken":"value",
"thirdToken":"value",
);
I keep running into errors trying to get specifically the userToken. I've tried get('Tokens[userToken]') but It's expecting a string only
How should I change this to be able to access any array key specifically
You can use array dereferencing and add a required index directly to value, returned by Session::get('Tokens'):
echo Session::get('Tokens')['userToken'];
you can try this too
$value = session('Tokens');
and you can use $value like and array and you'll be able to call each value with the index like
$value['userToken']
hope it help

PHP - get first value from array with single line using native functions

I have a function asdf() that returns an array ["key" => "value"]. I would like to print out value with one line, but reset() function suggested in similar questions does not work for me because reset only takes variable as a argument and doesent accept function. So if i try reset(asdf()) i get an exception: "Only variables should be passed by reference".
So my question is how can i print "value" from asdf() in a single line only using php native functions.
Actually reset function used to move the array's internal pointer to the first element, I think you must use current function that is return the current element in an array
Try like this
print current(asdf());
Try this:
current(array_values(asdf()));
It uses current to avoid the pass by reference error and array_values to ensure the array passed to current has the first element as it's current element.
Though unless you have a very good reason assigning the array to a variable and then using reset would be better.

php: accessing array dynamically using a string variable

Its like this
I have a variable that has an array index in it, for e.g.
$var = 'testVar["abc"][0]';
or
$var = 'testVar["xyz"][0]["abc"]';
or it could be anything at run time.
Now when I try to access this by using this php code:
echo $$var;
or
echo ${$var};
I get a warning saying Illegal offset at line ...
but if I use this code, it works
eval('echo $'.$var);
I do not want to use eval(). Is there any other way?
EDIT:
The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.
for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.
My php version is 5.1
According to the documentation, what you are trying to accomplish is not possible:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:
$a = "testVar";
echo ${$a}["xyz"][0]["abc"];

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.

Categories