3

I'm curious if I can assign a variable the value of a specific array index value returned by a function in PHP on one line.

Right now I have a function that returns an associative array and I do what I want in two lines.

$var = myFunction($param1, $param2);
$var = $var['specificIndex'];

without adding a parameter that determines what the return type is, is there a way to do this in one line?

0

2 Answers 2

4

In PHP 5.4, you can do this: $var = myFunction(param1, param2)['specificIndex'];.

Another option is to know the order of the array, and use list(). Note that list only works with numeric arrays.

For example:

function myFunction($a, $b){
    // CODE
    return array(12, 16);
}

list(,$b) = myFunction(1,2); // $b is now 16
Sign up to request clarification or add additional context in comments.

3 Comments

This is a good answer. The list(,$b) is probably not the best syntax to use for readability, though (in my opinion).
@user1477388: I know, but it was just an example.
Sadly my server uses PHP 5.2. thanks for the list option though
1

You could add an additional optional parameter and, if set, would return that value. See the following code:

function myFunction($param1, $param2, $returnVal = "")
{
    $arr = array();

    // your code here

    if ($returnVal)
    {
        return $arr[$returnval];
    }
    else
    {
        return $arr;
    }
}

3 Comments

Just wanted to say that there are better ways to solve the problem.
I'd make it a one-liner: return ( $returnVal) ? $arr[$returnVal] : $arr;
@FabianoLothor: Feel free to post them if you would. @nickb: Yes, that is also an option. For best readability, I posted mine as a simple if statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.