简体   繁体   中英

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?

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.

class Test {

  private $arr; //private property of object

  __construct(){

    //create arr in constructor   
    $this->arr=[];//create new array

    $this->arr['first'] = 'one';
    $this->arr['second'] = 'two';

  }

  /**
  /* get array
  **/
  public function getResults(){

     return $this->arr;
  }

  /**
  /* get single array element
  **/
  public function getResult($key) {

     return isset($this->arr[$key])?$this->arr[$key]:null;//return element on $key or null if no result
  }

}

$test = new Test();

print_r($test->getResult("second")); // Returns array element
//or second possibility but the same result
print_r($test->getResults()["second"]); // Returns array element

Few advices:

Create data structure in constructor ($arr in this particular case) because creating it on very results method call is not any kind of using objects or objective programming. Imagine that if array is created in results method then on every call new array is located in memory, this is not efficent, not optimal and gives no possibility to modify this array inside class Test.

Next in method results add parameter to get only this key what is needed and hide all array in private class property $arr to encapsulate it in object.

And last my private opinion for naming style:

Use camelCase when naming method names.

In PHP 5.4 and above:

print_r($test->results()['second']);

In older versions which you shouldn't be running as they are out of security maintenance:

$results = $test->results();
print_r($results['second']);

Edit: The first example originally said 5.6 and above but array dereferencing was introduced in 5.4! For the avoidance of doubt, 5.6 is the lowest php version within security maintenance.

In PHP an array value can be dereferenced from the array by its key.

$arr = ["foo" => "bar", "baz" => "quix"];

echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"

If the method/function returns an array the same can be done with the return value, whether by assigning the return value to a variable and using the variable to dereference the value by key, or by using function array dereferencing .

class Test {

    public function results() {

      return ["foo" => "bar", "baz" => "quix"];

    }     

}

$test = new Test;

$arr = $test->results();
echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"

// Using FAD (Function Array Dereferencing)

echo $test->results()["foo"]; // gives us "bar"
echo $test->results()["baz"]; // gives us "quix"

Of course there are two important caveats to using function array dereferencing.

  1. The function is executed each time you do it ( ie no memoziation )
  2. If the key does not exist or the function returns something other than array, you get an error

Which means it's usually safer to rely on assigning the return value to a variable first and then doing your validation there for safety... Unless you are sure the function will always return an array with that key and you know you won't need to reuse the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM