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.
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]
Previous to PHP 5.4 you could do this:
echo array_shift(explode('@', $var));
That would echo the first element of the array created by explode. But it is doing so without error checking the output of explode, which is not ideal.
list
can be used like this as well:
list($first) = explode('@', $var);
list(,$second) = explode('@', $var);
list(,,$third) = explode('@', $var);
Just use reset
like this
echo reset(explode('@', $var));