For example:
echo explode('@',$var); //but only echoing element 1 or 2 of the array?
Instead of:
$variable = explode('@',$var);
echo $variable[0];
Thank you.
On PHP versions that support array dereferencing, you can use the following syntax:
echo explode('@', $var)[0];
If not, you can use list():
list($foo) = explode('@', $var);
The above statement will assign the first value of the exploded array in the variable $foo.
Since PHP 5.4 you can write:
echo explode('@', $var)[0];
In earlier versions of PHP you can only achieve the behaviour with tricks:
echo current(explode('@', $var)); // get [0]
echo next(explode('@', $var)); // get [1]
Retreiving an element at an arbitrary position is not possible without a temporary variable.
Here is a simple function that can tidy your code if you don't want to use a variable every time:
function GetAt($arr, $key = 0)
{
return $arr[$key];
}
Call like:
echo GetAt(explode('@', $var)); // get [0]
echo GetAt(explode('@', $var), 1); // get [1]
echo current(explode('@', $var));@, so current() returns an empty string.Just use reset like this
echo reset(explode('@', $var));
exit(reset(explode('-', 'it-is-my-test')));
list()that doesn't use temporary variables or additional function calls -- eval.in/54886