PHP: Access Array Value on the Fly - php

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 ;)

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.

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

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.

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.

function doSomething()
{
return $somearray;
}
echo doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();

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));

Or something like this, if you need the array value in a variable
$variable = array('a','b','c');
$variable = $variable[$key];

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

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.

Related

$expode_top[] & $expode_bottom[] usage

I'm rewriting a PHP plugin, and there are functions called $expode_top[] & $expode_bottom[]. I understand what the normal explode function does, but what are these?
It seems to be impossible to find an answer on Google because it replaces the underscore with a space.
Those are array variables, not functions, they just happen to start with a keyword you are familiar with. Anything beginning with a $ is a variable in PHP.
Using [] will put the assigned variable into the "next" position of the array. For example:
$expode_top = array();
$expode_top[] = "testing";
if ( $expode_top[0] == "testing" ){
echo "it does equal testing";
}
As #gwillie rightly commented, it could also be a variable function - the name of the variable is replaced and then that function is executed. Second example:
$expode_top = "echo";
$expode_top("testing");
Is functionally the same as:
echo("testing");
Those are array variable names, not functions, as indicated by the $ and []. Also, neither exists as a function.

PHP Array: Syntax Variation

I ran into this php syntax the other day and I am not familiar with it. I *guessed it might doing a push, but I really don't know. Is this *exactly the same as array_push($b). If it is accomplishing something *similar, please explain how it is different.
$foo = array();
foreach($bar as $b)
{
$foo[] = $b; //push?
}
The only difference is the tiny bit of extra overhead involved in making a function call to array_push() vs making use of the language construct [] to append onto an array. They are functionally equivalent.
The difference between them from that function call is going to be utterly miniscule to the degree that you needn't worry about it unless you are doing it millions of times.
$foo[] = $b will be slightly faster due to the overhead of a function call (as Michael stated below).
Additionally, as stated in the manual, if the first argument to array_push is not an array a notice is raised. Using the array bracket notation will simply create a new array if it does not already exist.

explode without variables [duplicate]

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Access array element from function call in php
instead of doing this:
$s=explode('.','hello.world.!');
echo $s[0]; //hello
I want to do something like this:
echo explode('.','hello.world.!')[0];
But doesn't work in PHP, how to do it? Is it possible? Thank you.
As the oneliners say, you'll have to wait for array dereferencing to be supported. A common workaround nowadays is to define a helper function for that d($array,0).
In your case you probably shouldn't be using the stupid explode in the first place. There are more appropriate string functions in PHP. If you just want the first part:
echo strtok("hello.world.!", ".");
Currently not but you could write a function for this purpose:
function arrayGetValue($array, $key = 0) {
return $array[$key];
}
echo arrayGetValue(explode('.','hello.world.!'), 0);
It's not pretty; but you can make use of the PHP Array functions to perform this action:
$input = "one,two,three";
// Extract the first element.
var_dump(current(explode(",", $input)));
// Extract an arbitrary element (index is the second argument {2}).
var_dump(current(array_slice(explode(",", $input), 2, 1)));
The use of array_slice() is pretty foul as it will allocate a second array which is wasteful.
Not at the moment, but it WILL be possible in later versions of PHP.
This will be possible in PHP 5.4, but for now you'll have to use some alternative syntax.
For example:
list($first) = explode('.','hello.world.!');
echo $first;
While it is not possible, you technically can do this to fetch the 0 element:
echo array_shift(explode('.','hello.world.!'));
This will throw a notice if error reporting E_STRICT is on.:
Strict standards: Only variables should be passed by reference
nope, not possible. PHP doesn't work like javascript.
No, this is not possible. I had similar question before, but it's not

Is calling array() without arguments of any use?

From my C++ knowledge base, I tend to initialize arrays in PHP by typing:
$foo = array()
Or I may bring this custom from Javascript, anyway, is this of any use?
As there's no problem in doing this:
$foo[45] = 'bar' without initializing it as an array, I guess not.
PS: the tags improvement is really good
Yes it is. At the very least in improves readability of code (so that you don't need to wonder 'where does $foo come from? Is it empty, or is there anything in it?`.
Also it will prevent 'Variable '$a' is not set notices, or Invalid argument passed to foreach in case you don't actually assign any values to array elements.
Either method is perfectly acceptable. As mentioned, this practice of using the array() construct is typically carried over from another language where you initialize before populating. With PHP, you can initialize an empty array and then populate later, or you can simply establish an array by assignments, such as $variableName[0] = "x";.
#petruz, that's the best way to do this, no only it will save you from nasty PHP error messages saying that function expects the parameter to be an array but, IMHO, this is the best way to write code. I initialise a variable before using it
Initializing variables before use is good practice. Even if it is not required.
I've had problems (in older versions of PHP, haven't tried recently) where I was acting on array with array_push or something and PHP barked at me. As a general rule it's not necessary, but it can be safer, especially if you're dealing with legacy code; perhaps you're expecting $foo to be an array, but it's actually a boolean? Bad things ensue.
It's good practice. Sooner or later you'll encounter a situation where you might want to do something like this:
array_push($foo, '45');
Which will throw a notice, whereas:
$foo = array();
array_push($foo, '45');
won't.
With initialization:
$myArray = array();
if ($myBoolean) {
$myArray['foo'] = 'bar';
}
return $myArray;
Without initialization:
if ($myBoolean) {
$myArray['foo'] = 'bar';
}
return $myArray;
In the first case it's clear what you want to happen if $myBoolean is false. In the second case it is not and php may throw a warning when you try and use $myArray later. Obviously this is a simplified case, but in a complex case the "if" may be a few lines down and/or not even exist until someone comes along and adds it later without realizing the array wasn't initialized.
While not necessary, I have seen lack of initialization cause non-obvious logic problems like this in complex functions that have been modified a lot over time.

Are there pointers in php?

What does this code mean? Is this how you declare a pointer in php?
$this->entryId = $entryId;
Variable names in PHP start with $ so $entryId is the name of a variable.
$this is a special variable in Object Oriented programming in PHP, which is reference to current object.
-> is used to access an object member (like properties or methods) in PHP, like the syntax in C++.
so your code means this:
Place the value of variable $entryId into the entryId field (or property) of this object.
The & operator in PHP, means pass reference. Here is a example:
$b=2;
$a=$b;
$a=3;
print $a;
print $b;
// output is 32
$b=2;
$a=&$b; // note the & operator
$a=3;
print $a;
print $b;
// output is 33
In the above code, because we used & operator, a reference to where $b is pointing is stored in $a. So $a is actually a reference to $b.
In PHP, arguments are passed by value by default (inspired by C). So when calling a function, when you pass in your values, they are copied by value not by reference. This is the default IN MOST SITUATIONS. However there is a way to have pass by reference behaviour, when defining a function. Example:
function plus_by_reference( &$param ) {
// what ever you do, will affect the actual parameter outside the function
$param++;
}
$a=2;
plus_by_reference( $a );
echo $a;
// output is 3
There are many built-in functions that behave like this. Like the sort() function that sorts an array will affect directly on the array and will not return another sorted array.
There is something interesting to note though. Because pass-by-value mode could result in more memory usage, and PHP is an interpreted language (so programs written in PHP are not as fast as compiled programs), to make the code run faster and minimize memory usage, there are some tweaks in the PHP interpreter. One is lazy-copy (I'm not sure about the name). Which means this:
When you are coping a variable into another, PHP will copy a reference to the first variable into the second variable. So your new variable, is actually a reference to the first one until now. The value is not copied yet. But if you try to change any of these variables, PHP will make a copy of the value, and then changes the variable. This way you will have the opportunity to save memory and time, IF YOU DO NOT CHANGE THE VALUE.
So:
$b=3;
$a=$b;
// $a points to $b, equals to $a=&$b
$b=4;
// now PHP will copy 3 into $a, and places 4 into $b
After all this, if you want to place the value of $entryId into 'entryId' property of your object, the above code will do this, and will not copy the value of entryId, until you change any of them, results in less memory usage. If you actually want them both to point to the same value, then use this:
$this->entryId=&$entryId;
No, As others said, "There is no Pointer in PHP." and I add, there is nothing RAM_related in PHP.
And also all answers are clear. But there were points being left out that I could not resist!
There are number of things that acts similar to pointers
eval construct (my favorite and also dangerous)
$GLOBALS variable
Extra '$' sign Before Variables (Like prathk mentioned)
References
First one
At first I have to say that PHP is really powerful language, knowing there is a construct named "eval", so you can create your PHP code while running it! (really cool!)
although there is the danger of PHP_Injection which is far more destructive that SQL_Injection. Beware!
example:
Code:
$a='echo "Hello World.";';
eval ($a);
Output
Hello World.
So instead of using a pointer to act like another Variable, You Can Make A Variable From Scratch!
Second one
$GLOBAL variable is pretty useful, You can access all variables by using its keys.
example:
Code:
$three="Hello";$variable=" Amazing ";$names="World";
$arr = Array("three","variable","names");
foreach($arr as $VariableName)
echo $GLOBALS[$VariableName];
Output
Hello Amazing World
Note: Other superglobals can do the same trick in smaller scales.
Third one
You can add as much as '$'s you want before a variable, If you know what you're doing.
example:
Code:
$a="b";
$b="c";
$c="d";
$d="e";
$e="f";
echo $a."-";
echo $$a."-"; //Same as $b
echo $$$a."-"; //Same as $$b or $c
echo $$$$a."-"; //Same as $$$b or $$c or $d
echo $$$$$a; //Same as $$$$b or $$$c or $$d or $e
Output
b-c-d-e-f
Last one
Reference are so close to pointers, but you may want to check this link for more clarification.
example 1:
Code:
$a="Hello";
$b=&$a;
$b="yello";
echo $a;
Output
yello
example 2:
Code:
function junk(&$tion)
{$GLOBALS['a'] = &$tion;}
$a="-Hello World<br>";
$b="-To You As Well";
echo $a;
junk($b);
echo $a;
Output
-Hello World
-To You As Well
Hope It Helps.
That syntax is a way of accessing a class member. PHP does not have pointers, but it does have references.
The syntax that you're quoting is basically the same as accessing a member from a pointer to a class in C++ (whereas dot notation is used when it isn't a pointer.)
To answer the second part of your question - there are no pointers in PHP.
When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.
This does depend on the version of PHP you are using.
You can simulate pointers to instantiated objects to some degree:
class pointer {
var $child;
function pointer(&$child) {
$this->child = $child;
}
public function __call($name, $arguments) {
return call_user_func_array(
array($this->child, $name), $arguments);
}
}
Use like this:
$a = new ClassA();
$p = new pointer($a);
If you pass $p around, it will behave like a C++ pointer regarding method calls (you can't touch object variables directly, but that's evil anyways :) ).
entryId is an instance property of the current class ($this)
And $entryId is a local variable
Yes there is something similar to pointers in PHP but may not match with what exactly happens in c or c++.
Following is one of the example.
$a = "test";
$b = "a";
echo $a;
echo $b;
echo $$b;
//output
test
a
test
This illustrates similar concept of pointers in PHP.
PHP passes Arrays and Objects by reference (pointers). If you want to pass a normal variable Ex. $var = 'boo'; then use $boo = &$var;.
PHP can use something like pointers:
$y=array(&$x);
Now $y acts like a pointer to $x and $y[0] dereferences a pointer.
The value array(&$x) is just a value, so it can be passed to functions, stored in other arrays, copied to other variables, etc. You can even create a pointer to this pointer variable. (Serializing it will break the pointer, however.)

Categories