Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP: selecting values from a function that returns an array ( func()[0] ? )

  • 08-02-2004 05:13AM
    #1
    Registered Users, Registered Users 2 Posts: 1,842 ✭✭✭


    In perl, if I have a function that returns an array, I can select an element directly out of that by doing this:

    $a = func()[0];

    to put the first element into $a. in PHP, this causes a parse error, and I've been unable to find the right way to do this.

    At the moment, whenever I need to do this, I end up doing soemthing silly, like so:

    $a = func(); $a = $a[0];

    There has got to be a way to do this in php... but what is it?


Comments

  • Closed Accounts Posts: 66 ✭✭usualsuspect


    I don't know if it is possible to do what you ask; I use the syntax you already have.

    But to try and answer your question anyway, if it is a single-valued array, you could do

    $a=array_pop(func());

    if it is multivalued, supposing you want to get the third element you could do

    $a=array_pop(array_slice($func(),2,1));

    or write your own function to do it e.g.

    function array_get($array,$index) {
    return $array[$index];
    }
    $a=array_get(func(),2);

    However why incur the exepense of creating an array if you only need one of its values? Assuming you have control over the definition of func(), you could consider modifying it to take an additional argument, return a single value and skip any processing of the other values.


  • Registered Users, Registered Users 2 Posts: 1,842 ✭✭✭phaxx


    Ah thanks for that, I'd forgotten about array_pop.

    Ah yeah, I hadn't thought of an extra parameter to that function for just getting the first. I think I was just trying to do things the cleanest way, rather than the fastest. :)

    Thanks.


Advertisement