Home > other >  switching the order of three arguments in a function while keeping the same order in echo
switching the order of three arguments in a function while keeping the same order in echo

Time:11-20

I want to let the user to enter three different arguments without changing the order of the output

function check_status($a, $b, $c) {
  Some stuff
}

// Needed Output
echo check_status("User", 38, true); // "Hello User, Your Age Is 38, You Are Available For Hire"
echo check_status(38, "User", true); // "Hello User, Your Age Is 38, You Are Available For Hire"
echo check_status(true, 38, "Osama"); // "Hello User, Your Age Is 38, You Are Available For Hire"
echo check_status(false, "User", 38); // "Hello User, Your Age Is 38, You Are Not Available For Hire"

I have tried if statements didn't went well

CodePudding user response:

You can do a check on the type of the variable and concatenate the string to get the final one. I would do something like:

<?php
function check_status($a, $b, $c) {
  $name = null;
  $age = null;
  $availability = null;
  if (is_string($a)) $name = $a;
  if (is_string($b)) $name = $b;
  if (is_string($c)) $name = $c;
  
  if (is_int($a)) $age = $a;
  if (is_int($b)) $age = $b;
  if (is_int($c)) $age = $c;
  
  if (is_bool($a)) $availability = $a;
  if (is_bool($b)) $availability = $b;
  if (is_bool($c)) $availability = $c;

  $availableString = $availability ? "available" : "not available";
  echo "Hello $name, your age is $age, you are $availableString for hire \n";
}

check_status("John", 26, true);
check_status(26, "John", true);
check_status(true, 26, "John");
check_status(true, "John", 26);
check_status(false, "John", 26);
?>

The output is:

Hello John, your age is 26, you are available for hire   
Hello John, your age is 26, you are available for hire 
Hello John, your age is 26, you are available for hire 
Hello John, your age is 26, you are available for hire 
Hello John, your age is 26, you are not available for hire

It's not the shortest way to do it, it's an example. It's all about concatenating variables after checking the type. The concatenation could've be done with sprintf instead

CodePudding user response:

For, these cases you can use associative array as a function args.

function check_status($params) { 
      $availability = $params['availability'] ?? false;
      $name = $params['name'] ?? '';
      $age  = $params['age'] ?? 0;'enter code here'
      $availableString = $availability ? "available" : "not available";
      echo "Hello $name, your age is $age, you are $availableString for hire";
    }

  • Related