1

we've found a behavior that we don't know if it's right or not.

Please, view the next code:

<?php
$a = [];
$b = [];
$a[] = 'Hello';
$b[] = 'Bye';
if (isset($b[1]))
{
  $b1 = $b[1];
}
$a1 = defaultValue($a[1], 'again');
print_r($a);
print_r($b);
exit;
function defaultValue(&$var, $val)
{
  return isset($var) ? $var : $val;
}

The result was:

Array
(
    [0] => Hello
    [1] =>
)
Array
(
    [0] => Bye
)

Why the item $a[1] was created? Thanks!

2 Answers 2

3

You are passing $var into DefaultValue as reference (the & sign). This is place where $a[1] is created and set to null.

http://php.net/manual/en/language.references.php

Sign up to request clarification or add additional context in comments.

Comments

1

It's explained in the manual: http://php.net/manual/en/language.references.whatdo.php

Note: If you assign, pass, or return an undefined variable by reference, it will get created.

So, when you pass an undefined reference, it'll be created as null. Isset ensures that should be set and different of null. So the value "again" is returned.

3 Comments

Thanks. I've look for in the manual, obviously not with the right terms.
Thankis @gabriel-heming
@jhernandis You're welcome. That isn't a common knowledge.

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.