Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

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

Options
  • 08-02-2004 5:13am
    #1
    Registered Users 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 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