0

This is a simple question yet I'm unable to find an answer to this. I'm not looking for corrections to my code, simply education regarding this issue.

The array is defined before the first foreach begins so I can use it outside of the loop.

$arrayVar = array();

foreach ($variables as $key => $variable){
  $arrayVar = array(
    'name' => $squad['full_name'],
    'position' => $squad['position']
  ); 
}

This populates the array with data. However, when used in another loop, the array resets instead of appending to the end.

EDIT: John's answer resolves the issue. A simple inclusion of square brackets has saved me around 1000 lines.

1
  • 2
    When talking about code that doesn't behave as expected, you should include a minimal reproducible example - a short piece of code that actually demonstrates the problem, with the output you expected, and the output you actually got. Here, you've shown us the code you say is working OK, and the description of the problem is not very clear. It's therefore hard to tell if the answer you've been given addresses the problem you thought you had, or just points out a different problem in the code you've shown.
    – IMSoP
    Feb 15, 2021 at 14:26

1 Answer 1

5

You keep overwriting your array in every iteration instead of appending to it.

$arrayVar = array();

foreach ($variables as $key => $variable){
  $arrayVar[] = array( // <= Add to array instead of overwriting it
    'name' => $squad['full_name'],
    'position' => $squad['position']
  ); 
}
3
  • Thanks John, I appreciate the insight. So, I feel like array_push is what I should be using in remaining loops.
    – user10927737
    Feb 15, 2021 at 14:21
  • 2
    @M.Whitmore 1) The [] notation shown in this answer is equivalent to array_push, but more commonly used for its conciseness. 2) It's not about using it in "remaining loops", it's about the loop you've shown us here being incorrect.
    – IMSoP
    Feb 15, 2021 at 14:24
  • @IMSoP many thanks, I missed the notation initially from John's answer.
    – user10927737
    Feb 15, 2021 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy