Return function results based on condition - PHP

php function return multiple values
php function return array
php function return type
php function return string
php function return object
php return
php function return boolean
php function return multiple arrays

I have the following code

public function create(){
  return self::checkQuantity();
  return self::checkSameLocation();
  return self::someAnotherFunction();
  return self::someMoreFunction();
  ..
  ..
  ..

}

public function checkQuantity(){
  if(someCondition){
     return [foo,bar];
  }
}


public function checkSameLocation(){
  if(someCondition){
     return [foo,bar];
  }
}

I would like to return function inside create() only if it function inside it returns something else continue executing the create() function.

Based on the example:

  • create() gets called
  • if checkQuantity returns nothing then continue with checkSameLocation() without returning checkQuantity() function

NOTE: There could be multiple function calls inside create() sometimes, I would like to avoid using if statement checks.

public function create(){
    return self::checkQuantity()
           ?? self::checkSameLocation()
           ?? self::someAnotherFunction(); //and so on
}

See Null coalescing operator

Returning values - Manual, Values are returned by using the optional return statement. A function can not return multiple values, but similar results can be obtained by returning an array. As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL. Note: When overriding a parent method, the child's method must match any return type declaration on the parent.

public function create(){
  $data = function1();
  if ($data) { 
    return $data;
  }

  $data = function2();
  if ($data) { 
    return $data;
  }

  $data = function3();
  if ($data) { 
    return $data;
  }

  // ...

  return function42();
}

This can lead to another solution like:

public function create(){
  $functions = ['func1', 'func2', 'func3',]; // etc
  foreach ($functions as $func) {
    $data = $func();
    if ($data) { 
      return $data;
    }
  }
}

return - Manual, If called from within a function, the return statement immediately ends Calling return with parentheses but with no arguments will result in a parse error. Inside a function values are returned by using return statement. After return statement function end its execution immediately and pass control back to the line from which it was called. If you want to return multiple values in PHP then make an array and return it. NOTE – Only single return statement is used inside a function.

Something like this:

(in this case, I've moved all your check code into polymorphic classes; the same could be achieved with methods in the current class per your question, but I think it's neater this way)

$checks = [new checkClass1, new checkClass2, new checkClass3, ...];

foreach ($checks as $check) {
    $result = $check->runCheck();
    if ($result) {
        return $result;
    }
}

if - Manual, If expression evaluates to TRUE , PHP will execute statement, and if it evaluates to FALSE Result (depending on hardware configuration): If assign var to function that returns 0 as integer or 0 as string 'if' statement condition works as false. PHP Built-in Functions. PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task. Please check out our PHP reference for a complete overview of the PHP built-in functions.

You need an if and a temporary variable.

public function create(){
  $a = self::checkQuantity();
  if(empty($a)) { 
    return self::checkSameLocation();
  } else {
    return $a;
  }
}

public function checkQuantity(){
  if(someCondition){
     return [foo,bar];
  }
}


public function checkSameLocation(){
  if(someCondition){
     return [foo,bar];
  }
}

PHP return statement, Description. PHP return statement immediately terminates the execution of a function when it is called from within that function. This function is� It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C: if (expr) statement. As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE , PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

This looks like the perfect use case for the null coalescing operator

public function create(){
  return self::checkQuantity() ?? self::checkSameLocation() ?? self::someAnotherFunction() ?? return self::someMoreFunction()...
}

You can chain as many function calls as you want. That line will return the first value that's not null. Since returning nothing from a function effectively equals returning a null value, it'll work as you want.

The List of the 10 Most Common Mistakes That PHP Developers , PHP makes it relatively easy to build a web-based system, which is much of the As a result, when we go through the second foreach loop, “weird stuff” need to modify the getValues() function to return a reference to the $values array itself. “out of memory” condition in libmysqlclient when using PHP's mysql extension. Function-return value in PHP A function can return a value using the return statement in conjunction with a value or object. In return value function, return keyword is used to return a value from a function. In return value function, return stops the execution of the function and sends the value back to the calling code.

Using a function's return value as an if condition, good practice , In the code you posted, there's no reason to store the function result in a variable before using it. (Unless perhaps the name of the variable is sufficiently� PHP conditional statements You can use PHP If and PHP Else if conditional statements in PHP to perform different actions. These actions are based on the logic you want to perform using your code and get the result of the action.

Should I return from a function early or use an if statement , Likewise, if a condition generates a giant if block in function I will have it breakout With one entry and multiple exists, you return when you have your result and don't D-language gives you proper built-in scope-exit guards and therefore is� Eloquent: Getting Started. Introduction; Defining Models. Eloquent Model Conventions; Default Attribute Values; Retrieving Models. Collections; Chunking Results

How to return multiple values from function in PHP?, PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control Display the result. Return Value: A random integer between min (or 0) and max (or getrandmax() inclusive) Return Type: Integer: PHP Version: 4+ PHP Changelog: PHP 7.1: The rand() function is an alias of mt_rand(). PHP 4.2.0: The random number generator is seeded automatically.

Comments
  • Without doing if checks, because if there are 10 functions calls that would make it messy.
  • Without if checks you can't check if nothing returned from first function
  • Im not sure what it is your functions return, are these functions wrapped in a class? You cant check if nothing returned from a function because it will always return null.
  • In terms of OOD, I guess a suitable solution would be chain of responsibility
  • @AndriiFilenko thanks, I will look into it.
  • This is much better than if.. else, much cleaner. I was looking for this. Thanks.
  • Thanks for the answer. But coalesce operator is much cleaner approaches for my use case.
  • What if, there is more than 2 functions? Please check updated question.