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);
Damenace
  • 75
  • 8

2 Answers2

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)
arkascha
  • 41,620
  • 7
  • 58
  • 90
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.

thchp
  • 2,013
  • 1
  • 18
  • 33