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:

    [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:

$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.

Leave a Reply