Home > OS >  how to simplify the same code in two else condition PHP
how to simplify the same code in two else condition PHP

Time:02-17

There are two 'else' condition with the same code, so how to simplify this code?

if(!empty($data))
{
  $getData = $this->getData($data);
  if(!empty($getData))
  {
    $response = $getData->name;
  }
  else
  {
    $response = $this->getRequest($value);
  }
}
else
{
  $response = $this->getRequest($value);
}

return $response;

CodePudding user response:

This should help

$response = $this->getRequest($value);

if(!empty($data)){
    $getData = $this->getData($data);
    if(!empty($getData))
    {
        $response = $getData->name;
    }
}

return $response;

CodePudding user response:

You could do this:

if(!empty($data)) {
    $getData = $this->getData($data);
    if(!empty($getData)) {
        $response = $getData->name;
    }
}

if ($response == null) { // Or check if the $response is not filled yet
    $response = $this->getRequest($value);
}

return $response;

CodePudding user response:

Get the response from getData, and in a second step check if $response is set, and if not get the value from _ getRequest_:

if (!empty($data)) {
  $getData = $this->getData($data);
  if (!empty($getData)) {
    $response = $getData->name;
  }
}

$response = $response ?? $this->getRequest($value);

CodePudding user response:

if(!empty($data) && ($getData = $this->getData($data)) && !empty($getData))
{
  $response = $getData->name;
}
else
{
  $response = $this->getRequest($value);
}

return $response;
  •  Tags:  
  • php
  • Related