0

I get data from query and running a foreach loop on it.

foreach($result as $data)
{
    $myVar[$data->flag][$data->year]['totalActions'] += $data->totalActions;
}

And getting this error Undefined variable: myVar

When I create a variable before loop like $myVar = []

Then it gives me the error Undefined index: All

Here All is value of $data->flag

How to handle this?

3
  • Where is contractDetails here? Commented Mar 2, 2021 at 14:59
  • sorry, it is $myVar. Edit my question now Commented Mar 2, 2021 at 15:01
  • what is the data type of $data->year (string ?) and $data->totalActions (int ?) ? Commented Mar 2, 2021 at 15:30

2 Answers 2

2

first of all you need to define $myVar (before foreach) as you did: $myVar = [];

second you need to define/isset $myVar[$data->flag], $myVar[$data->flag][$data->year] and $myVar[$data->flag][$data->year]['totalActions'] inside the foreach

in summery the whole snippet of code will be like so:

$myVar = [];

foreach($result as $data)
{
    $myVar[$data->flag] = isset($myVar[$data->flag]) ? $myVar[$data->flag] : '';
    $myVar[$data->flag][$data->year] = isset($myVar[$data->flag][$data->year]) ? $myVar[$data->flag][$data->year] : '';
    $myVar[$data->flag][$data->year]['totalActions'] = isset($myVar[$data->flag][$data->year]['totalActions']) ? $myVar[$data->flag][$data->year]['totalActions'] : 0;
    $myVar[$data->flag][$data->year]['totalActions'] += $data->totalActions;
}

or simply ignore the the errors by using @ before $myVar so you can do so:

$myVar = [];

foreach($result as $data)
{
    @$myVar[$data->flag][$data->year]['totalActions'] += $data->totalActions;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just create and init the $myVar before the foreach and init with the zero value if key isn't exists.

$myVar = [];

foreach($result as $data)
{
    if (!isset($myVar[$data->flag][$data->year])) {
        if (!isset($myVar[$data->flag])) {
            $myVar[$data->flag] = [];
        }

        $myVar[$data->flag][$data->year] = ['totalActions' => 0];
    }

    $myVar[$data->flag][$data->year]['totalActions'] += $data->totalActions;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.