Pregunta

So I am using a function which is used in two different places in a HTML, shown below.

function remaining($expDate,$output){
 $dStart = new DateTime(date('Y-m-d'));
    $dEnd  = new DateTime(date('Y-m-d ',strtotime($expDate)));

    $dDiff = $dStart->diff($dEnd);
     $dDiff->format('%R'); 

  if($output = "return"){
        return $dDiff->days;
    }else{
        echo $dDiff->days;}
}
<div 
  class="progress-bar <?php if(remaining($expDate,"return")==90){echo"progress-bar-success";}else{echo "progress-bar-danger";}?> 
  role="progressbar" 
  aria-valuenow="40" 
  aria-valuemin="0" aria-valuemax="100" 
  style="width: <?php remaining($expDate,"echo") ?>%">

When I return the value style part does not work, when I echo then in the if() statement I get the value :( So I tried to add a second argument and give a relative output. I am obviously missing something here but could not figure it out :( Would you give me a hint on variable output on a function? Or may be a better way to achieve this:)

¿Fue útil?

Solución

The problem is the if statement

This is an attribution not a comparison
if( $output = "return" ){ ...

Should be something like:

function remaining($expDate,$output){
    $dStart = new DateTime(date('Y-m-d'));
    $dEnd  = new DateTime(date('Y-m-d ',strtotime($expDate)));
    $dDiff = $dStart->diff($dEnd);
    return $dDiff->days;
}

AH!! By the way the code above works, you are not managing in getting it to work because you forgot to do this: <?php echo remaining()... ?> you forgot the echo!

Regards.

Otros consejos

if($output = "return")

Will always be true, correct it to

if($output == "return")

so the program compares and return either TRUE or FALSE

if($output = "return"){

needs to be

if($output == "return"){

if you put

if($output = "return"){

then you effectively set $output to equal return (which will always return true!)

Your if statement seems bad. You are using '=' which does not sound like the 'equals' operator in PHP. So just replace '=' in your condition with '=='.

You may also prefer to pass a simple boolean here (true / false) instead of a string, but that is up to you.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top