Tag Archives: C programming language

It’s Not True that PHP Arrays are Copied by Value

PHP, Arrays & Passing by Reference

Do you know that objects in PHP5 are passed by reference, while arrays and other scalar variables are passed by value? Yes, you know it, but it’s not exactly true. Let’s see some example and let’s try to answer few questions.

// depending on the machine but both lines return
// expectedly equal values: 331208
 
// 331208
echo memory_get_usage();
echo memory_get_usage();

These two lines of code, expectedly return the same value (in my case 331208), which shows us that because nothing happened in between them the memory usage isn’t growing. Let’s now put some code in between them.

echo memory_get_usage(); // 331616
$a = 10;
echo memory_get_usage(); // 331696

Continue reading It’s Not True that PHP Arrays are Copied by Value

Thing to Know About PHP Arrays

Consider the following case. We have an array with identical keys.

$arr = array(1 => 10, 1 => 11);

What happens when the interpreter reaches this line of code? This is not a syntax error and it is completely valid. Very similar, but more interesting case is when we have an array of identical keys, where those identical keys are represented once as an integer and then as a string.

Keys in PHP arrays are not type sensitive, so pay attention when using them!
Keys in PHP arrays are not type sensitive, so pay attention when using them!

$arr = array(1 => 10, "1" => 11);

Now several questions arise. First of all, how many elements have this array? Two or one. This can be easily verified by checking what count() will return. Continue reading Thing to Know About PHP Arrays