-2

I have a PHP class containing a 2-dimensional array:

      class ArrApp
      {
        private $cms = [
                         'S' => 'A',
                         'V' => []
                       ];

        ...
      }

The class has a method to append a specified element in the inner array:

        public function App($elm)
        {
          $V = $this->cms[0]['V'];

          array_push($V, $elm);
          $this->Prt();
        }

The Prt() method simply prints the outer array:

        public function Prt()
        {
          print_r($this->cms);
          echo '<br>';
        }

I instantiate the class and try to append an element in the inner array:

      $aa = new ArrApp();
      $aa->Prt();

      $aa->App(1);
      $aa->Prt();

However, the O/P shows an empty inner array:

Array ( [S] => A [V] => Array ( ) )
Array ( [S] => A [V] => Array ( ) )
Array ( [S] => A [V] => Array ( ) )

  1. Why is this happening? Is it related to a 'pass by value' / 'pass by reference' issue?
  2. How do I fix this?
1
  • 1
    Arrays in PHP aren't passed by reference, assigning them to another variables creates a copy [on write]. Commented Aug 30, 2021 at 8:31

1 Answer 1

1

You try to access element 0 in an associative array you cannot do that.

public function App($elm) {
    $V = $this->cms[0]['V']; // here
Sign up to request clarification or add additional context in comments.

1 Comment

Mueller, thanks. I fixed that and it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.