2

Why am I getting different outputs through print_r in the following two cases!!? This is a bug in php? Is php unable to execute complex hierarchical functions called inside functions?

CASE 1 :
$aa='2,3,4,5,5,5,';
$aa=array_unique(explode(',',$aa));
array_pop($aa);
print_r($aa);

CASE 2 :
$aa='2,3,4,5,5,5,';
array_pop(array_unique(explode(',',$aa)));
print_r($aa)

In the first case, the output is an exploded array :

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 ) 

In the second case, the output is string :

2,3,4,5,5,5,
Vishal
  • 53
  • 6

2 Answers2

7

This is because array_pop alters its input, and you're passing it a temporary variable (not $aa).

Note the signature in the documentation: array_pop ( array &$array ) - the & means it takes a parameter by reference, and it alters that input variable.

Compare with the other two functions:

array explode ( string $delimiter , string $string , int $limit )

and

array array_unique ( array $array , int $sort_flags = SORT_STRING )

In the first case you update $aa with the output of array_unique(), and then pass that to array_pop to be altered.

In the second case the output of array_unique() will be the same, but this temporary value isn't assigned to a variable & therefore it's forgotten after array_pop is called.

It's worth noting that in that in PHP (unlike say, C++), passing by reference is actually slower than passing by value and therefore is only ever used to modify the input parameter of a function.

Community
  • 1
  • 1
John Carter
  • 52,342
  • 26
  • 107
  • 142
0

In the first case you alter variable as in line 2 bs assigning a new value with the assignment operator =

yunzen
  • 31,553
  • 11
  • 69
  • 98