PHP: Access Array Value on the Fly [duplicate]
Asked Answered
A

9

50

In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:

// the following results in an error:
echo array('a','b','c')[$key];

// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];

This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)

Aurochs answered 16/8, 2008 at 12:42 Comment(1)
Works as of PHP v5.4, illegal syntax in PHP <= v5.3Pedestal
K
19

I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

$variable = array('a','b','c');
echo $variable[$key];
unset($variable);

Or, you could write a small function:

function indexonce(&$ar, $index) {
  return $ar[$index];
}

and call this with:

$something = indexonce(array('a', 'b', 'c'), 2);

The array should be destroyed automatically now.

Kayceekaye answered 16/8, 2008 at 12:55 Comment(1)
@onnodb, Strict Standards: Only variables should be passed by reference for your function indexonce. Why do you add the & reference?Franglais
W
40

The technical answer is that the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they're using an inflexible parser generator or they simply don't want to break some sort of backwards compatibility.

Here are a couple more examples of invalid subscripts on valid expressions:

$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.

function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.
Womanly answered 28/8, 2008 at 9:58 Comment(4)
There was a change proposal at least for the second syntax, but it was rejected: wiki.php.net/rfc/functionarraydereferencingMilden
Status is now changed to accepted wiki.php.net/rfc/functionarraydereferencingCollate
This answer is no longer accurate. As of 5.5, PHP supports constant/array/string dereference wiki.php.net/rfc/constdereferenceYuonneyup
@John, Why did you say it'll "break some sort of backwards compatibility"? They did introduced it in 5.4 and so, what kind of backwards compatibility issues are there?Franglais
Y
23

This is called array dereferencing. It has been added in php 5.4. http://www.php.net/releases/NEWS_5_4_0_alpha1.txt

update[2012-11-25]: as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays

Yuonneyup answered 25/10, 2011 at 11:28 Comment(0)
K
19

I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

$variable = array('a','b','c');
echo $variable[$key];
unset($variable);

Or, you could write a small function:

function indexonce(&$ar, $index) {
  return $ar[$index];
}

and call this with:

$something = indexonce(array('a', 'b', 'c'), 2);

The array should be destroyed automatically now.

Kayceekaye answered 16/8, 2008 at 12:55 Comment(1)
@onnodb, Strict Standards: Only variables should be passed by reference for your function indexonce. Why do you add the & reference?Franglais
S
6

This might not be directly related.. But I came to this post finding solution to this specific problem.

I got a result from a function in the following form.

Array
(
    [School] => Array
            (
                [parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a
            )
)

what i wanted was the parent_id value "9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a". I used the function like this and got it.

array_pop( array_pop( the_function_which_returned_the_above_array() ) )

So, It was done in one line :) Hope It would be helpful to somebody.

Spry answered 23/12, 2011 at 7:36 Comment(1)
This only works on the last value, and you will be removing the value from the original array.Franglais
G
2
function doSomething()
{
    return $somearray;
}

echo doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();
Gaskell answered 18/2, 2011 at 10:40 Comment(1)
How could you do get(1) on an array? Fatal error: Call to a member function get() on a non-object in file.php on line 21Franglais
D
1

actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:

$myvar = array_shift(array_splice(myfunc(),2));
Dragonhead answered 26/5, 2010 at 11:50 Comment(0)
E
0

Or something like this, if you need the array value in a variable

$variable = array('a','b','c');
$variable = $variable[$key];
Equivalent answered 13/8, 2009 at 6:29 Comment(0)
P
0

There are several oneliners you could come up with, using php array_* functions. But I assure you that doing so it is total redundant comparing what you want to achieve.

Example you can use something like following, but it is not an elegant solution and I'm not sure about the performance of this;

   array_pop ( array_filter( array_returning_func(), function($key){    return $key=="array_index_you_want"? TRUE:FALSE;    },ARRAY_FILTER_USE_KEY ) );

if you are using a php framework and you are stuck with an older version of php, most frameworks has helping libraries.

example: Codeigniter array helpers

Popper answered 24/2, 2016 at 11:46 Comment(0)
D
0

though the fact that dereferencing has been added in PHP >=5.4 you could have done it in one line using ternary operator:

echo $var=($var=array(0,1,2,3))?$var[3]:false;

this way you don't keep the array only the variable. and you don't need extra functions to do it...If this line is used in a function it will automatically be destroyed at the end but you can also destroyed it yourself as said with unset later in the code if it is not used in a function.

Daddy answered 10/8, 2018 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.