2

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ted
  • 487
  • 2
  • 12
  • 23
  • where do you define $info? Pass it to your function, or (dirty) use global: `function tomato(){ global $info; [...]` – Green Black Mar 01 '13 at 23:53
  • please consider to accept an answer (click tick mark on the left) if it actually answered your question – michi Apr 14 '13 at 12:57

2 Answers2

3

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];
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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]);
michi
  • 6,565
  • 4
  • 33
  • 56