0

Forgive the word game.

I have to cycle an array and sum the values, then multiply for the price (i already know how to do that).

The object is composed of 64 fields called val1, val2, val3 etc .. each field has a simple_array with the value of the quantity.

I get these data from the database using doctrine.

    $item = $this->getDoctrine()->getRepository(ExpertationsAdvanced::class)->findBy(['father' => $id]);

    dump($item[0]->getVal1());

        for($i = 1; $i < 64; $i++) {
            dump(${'$item[0]->getVal' . $i . '()'});
            $i++;
            if(${'$item[0]->getVal' . $i . '()'} == null) {
                $return = '0';
            } else {
                $return = array_sum(${'$item[0]->getVal' . $i . '()'} );
            }

            dump($return);
        }

the first dump return the array i'm requesting for, with no problems, but in the forloop, i get erro Notice: Undefined variable: $item[0]->getVal1().

I think I'm using the wrong logic but maybe worked so mutch time and can't see a way.

1
  • Have u done search before asking? Commented Oct 23, 2018 at 17:30

1 Answer 1

0

First of all if you have 64 fields, you should have(read docs for more info):

for($i = 1; $i <= 64; $i++) {

Secondary, you don't need to increment $i inside of loop

$i++;

To get the value:

$item[0]->{"getVal{$i}"}();
// OR
$method = "getVal{$i}";
$item[0]->$method();

Result will be:

for($i = 1; $i <= 64; $i++) {
    $array = $item[0]->{"getVal{$i}"}();

    $return = is_array($array) ? array_sum($array) : 0;
    dump($return);
}
Sign up to request clarification or add additional context in comments.

2 Comments

He will overwrite the return in every iteration and in the end return only for the last field, I think this is not what he wants. Probably he wants to use foreach loop and declare variable before loop and then add to it inside loop :).
May be, but based on description he knows how to do that : I have to cycle an array and sum the values, then multiply for the price (i already know how to do that).

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.