Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing array values without square brackets in php

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?

like image 262
amb Avatar asked Mar 23 '10 01:03

amb


People also ask

What is difference between array and [] in PHP?

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 [].

What does array [] mean in PHP?

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.

Why square brackets are used in array?

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.


1 Answers

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();
like image 158
nickf Avatar answered Oct 20 '22 09:10

nickf