JROB JROB - 3 months ago 12
PHP Question

PHP: How to get single value from array that was returned from a class?

class Test {

public function results() {

$return['first'] = 'one';
$return['second'] = 'two';

return $return;

}

}

$test = new Test;

print_r($test->results()); // Returns entire array


I just want to return a single specified element from the array, such as the value of key "second". How do I do this without sifting through the entire array after it's returned?

Answer

I just want to return a single specified element from the array, such as the value of key "second"

Pass in an argument to identify which element to return, and return that (or false if it doesn't exist - for example);

public function results($key = null)
{
    $return['first'] = 'one';
    $return['second'] = 'two';

    // check the key exists
    if (!array_key_exists($key, $return)) {
        return false;
    }

    return $return[$key];
}

Then:

print_r($test->results('second')); // two

How do I do this without sifting through the entire array after it's returned?

It's important to note that you do not need to "sift through the entire array" to retrieve a value by its key. You know the key, so you can access it directly.

Comments