Shortcut to get element from returned array by specific index / key?

I feel there is a way to do this with a shortcut:

$date_array = explode("-", $date); $day = $date_array[2]; 

Sort of:

 $day = explode("-", $date)[2]; 

Basically get an answer and set it to something?

I don’t remember, but there aren’t a bunch of weird "=" things like concatenation .= . Are there any other shortcuts? It seems that I could not find an article on Google with all the shortcuts.

I don’t like doing $date_array when all I really want is $day makes me feel like my code is not efficient.

EDIT: Changed the name to be more universal, can't come up with anything good.

+4
source share
3 answers

As the new features on the PHP 5.4 page show, the syntax you proposed (called dereferencing function arrays) is now possible with this version.

 $day = explode("-", $date)[2]; 

This will not work, however, in 5.3 or earlier.

+5
source

Variable list

list(,,$day) = explode("-", $date);

list() takes an array and parses it into variables ... you can skip items that you don't need, leaving the item empty, as I did above. Must do what you need. Another type of syntax that you tried to use in php (at least not in the versions that I have ever used) is more JavaScript type notation.

Alternative

Just in case, you are interested in another solution for what you are trying (unless it is just an example to illustrate):

 /// this will give you the current day based on server time $day = date('d'); /// this will work from an existing Ymd date $day = date('d', strtotime($date)); 

Now, if converting the Ymd date string to a timestamp is faster than splitting the string and pulling it out of it - only a speed test will say (I think the split will win). But for me this is better, because I can not help but think about other elements of the array that were separated and then simply lost to oblivion;)

+5
source

After php5.4 you can do this:

 $day = explode("-", $date)[2]; 

Prior to php5.4, you can use list .

 list(,,$day) = explode("-", $date); 
0
source

Source: https://habr.com/ru/post/1433753/


All Articles