In php how can I access an array's values without using square brackets around the key? My particular problem is that I want to access the elements of an array returned by a function. Say function(args) returns an array. Why is $var = function(args)[0]; yelling at me about the square brackets? Can I do something like $var = function(args).value(0); or am I missing something very basic?
Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].
Advertisements. An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.
As the others have said, you pretty much have to use a temporary variable:
$temp = myFunction();
$value = $temp[0];
But, if know the structure of the array being returned it is possible to avoid the temporary variable.
If you just want the first member:
$value = reset(myFunction());
If you want the last member:
$value = end(myFunction());
If you want any one in between:
// second member
list(, $value) = myFunction();
// third
list(, , $value) = myFunction();
// or if you want more than one:
list(, , $thirdVar, , $fifth) = myFunction();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With