1

Why does PHP create a new array when I push an element?

$a = array();
$b = $a;

$b[] = "Hello!";
echo count($a);
echo count($b);

Here you would expect the count for $a and $b to be equal, but they are not.

6
  • They are not equal since $a is empty and $b have 1 value. Commented Aug 8, 2013 at 8:37
  • 1
    what is unexpected here exactly? I don't see anything wrong Commented Aug 8, 2013 at 8:37
  • In the vast majority of popular programming languages, assignments of an array-like object would be by reference. Commented Aug 8, 2013 at 8:41
  • which language doing that?? Commented Aug 8, 2013 at 8:42
  • @Akam well, javascript) However, Array in javascript is an Object, but in php it is not. Commented Aug 8, 2013 at 8:45

2 Answers 2

3

By default, PHP is copying values when assigning them. If you want a reference, you can use the & operator:

$a = array();
$b = &$a;

$b[] = "Hello!";
echo count($a);  // prints 1
echo count($b);  // prints 1
Sign up to request clarification or add additional context in comments.

1 Comment

@CORRUPT agreed, that's why I added the quotes. I'll update my answer to avoid confusion.
0

This is because $a and $b are two separate variables, when you assign $b = $a you are only copying the contents of $a to $b, not making them both point to the same array.

To do this, you need to pass by references instead:

$b = &$a;

In this case, $b points to the reference to $a, which means they both point to the same array, any change to one will change on both.

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.