Ted
Ted

Reputation: 497

php - if condition failing every time

I have a simple php function. however, it fails every time, no matter what.

function for determining tomato pic

echo "$info[2]";
function tomato()
{
    if(intval($info[2]) > 60)
        return "fresh";
    else if(intval($info[2]) < 60)
        return "rotten";
}

it echo 95 on the page but then returns "rotten". any idea whats up with this?

Upvotes: 2

Views: 279

Answers (2)

michi
michi

Reputation: 6625

you have to make the variable known to the function, try

function tomato() {
    global $info;
    ...

alternatively, pass the value as argument to the function:

function tomato($tomatocondition) {
    if(intval($tomatocondition) > 60)
        return "fresh";
    else if(intval($tomatocondition) < 60)
        return "rotten";

and call it...

echo tomato($info[2]);

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324730

Functions do not inherit variables from the parent scope. There are a few ways around this:

1: Pass them as a parameter

function tomato($info) {...}
tomato($info);

2: If it is an anonymous function, use the use clause

$tomato = function() use ($info) {...}

3: (Not recommended) Use the global keyword to "import" the variable

function tomato() {
    global $info;
    ...
}

4: (Very bad idea, but added for completeness) Use the $GLOBALS array

function tomato() {
    // do stuff with $GLOBALS['info'][2];
}

Upvotes: 3

Related Questions