0

Is there a way to use if/else code multiple times for different variables? This is just a example because I don't know how to search for it or if it even exist? Can someone point me in the right direction?

function value(){
if ($value > 999 && $value <= 999999) {
    $value = number_format($value / 1000,1) . 'K';
  } elseif ($value > 999999) {
    $value = number_format($value / 1000000,1) . 'mln';
  } else {
    $value;
  }
}

  value($variable1);
  value($variable2);
  value($variable3);
4
  • Php providing switch function for the task Commented Jul 19, 2017 at 12:54
  • 1
    Does this function work as you expect? Commented Jul 19, 2017 at 12:56
  • 2
    You need to define a call argument in the function declaration. That is the whole point of functions. Commented Jul 19, 2017 at 12:56
  • check this: stackoverflow.com/questions/10221694/… Commented Jul 19, 2017 at 12:57

2 Answers 2

3

You need to define a call argument (parameter) in the function declaration. That is the whole point of functions:

<?php
function formatValue($value){
if ($value > 999 && $value <= 999999) {
    return number_format($value / 1000,1) . 'K';
  } elseif ($value > 999999) {
    return number_format($value / 1000000,1) . 'mln';
  } else {
    return $value;
  }
}

$someValue = 8888;
var_dump(formatValue($someValue));
var_dump(formatValue(555555555));
var_dump(formatValue((2*$someValue)+1000000));
var_dump(formatValue(-200));

The output of above code is:

string(4) "8.9K"
string(8) "555.6mln"
string(6) "1.0mln"
int(-200)
Sign up to request clarification or add additional context in comments.

Comments

0

The value function has to take one parameter ($value).

Your function should be

    function value(&$value){
       if ($value > 999 && $value <= 999999) {
          $value = number_format($value / 1000,1) . 'K';
       } elseif ($value > 999999) {
          $value = number_format($value / 1000000,1) . 'mln';
       } else {
          $value;
       }
}

You have to pass $value as a reference since you assign something to it and you want to get it outside the function.

You could also return number_format($value / 1000,1) . 'K'; instead of assigning it to $value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.