Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does php arrow function work exactly with print function?

we know that print function always return 1, so when using it like this:

$arr = [10, 20, 30, 40];
$arr2 = array_map(fn ($num) => print $num, $arr);

The output will be like this:

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

because the returned value will be assigned to array elements,
but when I use it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$var = fn ($name, $age) => print "Hello my name is $name and I'm $age years old";
$var("Ahmad", 22);

The output will be:

//Output: Hello my name is Ahmad and I'm 22 years old

shouldn’t the output here be 1?

>Solution :

The value is still 1.

If you dump the value you will get 1:

var_dump($var("Ahmad", 22));
//Return int(1) 

However the result of your arrow function is not used and you just print a message. That’s the reason why you think the value of print is different.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading