0

I have a problem in using of array as a variable in nested if..else.. conditions. Its used to create custom web-service APIs. Here is the structure of code:

if (condition) {
    // code to be executed in case of true

    if (condition) {
        // code to be executed in case of true

        $result['key1'] = $variable1;
        $result['key2'] = $variable2;
        $result['key3'] = $variable3;

    } else {
        // code to be executed in case of false
    }

} else {
    $result['error'] = 'Something went wrong!!!';
}
echo json_encode($result);    // line 121

On execution of code it displays the following error:

Notice: Undefined variable: result in C:\xampp.. on line 121

bofanda
  • 10,386
  • 8
  • 34
  • 57

2 Answers2

0

Variables need to be declared before using it inside functions like json_encode()! Do it this way:

$result = array();
if (condition) {
    // code to be executed in case of true

    if (condition) {
        // code to be executed in case of true

        $result['key1'] = $variable1;
        $result['key2'] = $variable2;
        $result['key3'] = $variable3;

    } else {
        // code to be executed in case of false
    }

} else {
    $result['error'] = 'Something went wrong!!!';
}
echo json_encode($result);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

U need to declare your variable first if you are directly entering the value to an array.

$result = array();

if (condition) {
    // code to be executed in case of true

    if (condition) {
        // code to be executed in case of true

        $result['key1'] = $variable1;
        $result['key2'] = $variable2;
        $result['key3'] = $variable3;

    } else {
        // code to be executed in case of false
    }

} else {
    $result['error'] = 'Something went wrong!!!';
}
echo json_encode($result);    // line 121
RickyHalim
  • 295
  • 6
  • 22