program2.php

<html>
<header>
</header>

<body>

<?php 

function Multiply($x, $y)
    {
    echo $x * $y;
    }

echo 'Multiply : '.Multiply(2,3).'<br><br>';

?>  

</body>

</html>

Why the result of the above program is :

6Multiply :

instead of

Multiply : 6

Any clue?

Dani AI

Generated

Short answer: the function prints 6 before the outer echo prints Multiply : because the function uses echo internally and returns no value. In the posted snippet calls Multiply(2,3) inside a string concatenation; PHP executes that call first, the function echoes 6 immediately, then it returns NULL (functions without return return NULL), so the concatenation becomes Multiply : + empty string. As said, it’s an order-of-execution effect, and ’s suggestion to return the value is the simplest fix.

A clear fix is to have the function return the computed value and let the caller handle output:

<?php
function prod($a, $b) {
    return $a * $b;
}

echo 'Multiply : ' . prod(2, 3) . "<br><br>";
?>

If you cannot change the function because it’s from third‑party code that already echoes, capture its output with output buffering and then concatenate:

<?php
function printProd($a, $b) {
    echo $a * $b;
}

ob_start();
printProd(2, 3);
$result = ob_get_clean();

echo 'Multiply : ' . $result . "<br><br>";
?>

Practical rules: prefer returning computed values from business/utility functions and reserve echo for presentation. Remember that echo is a language construct that doesn’t produce a usable return value, and functions without return produce NULL, which concatenates as an empty string. Use var_dump() when debugging return values or call order.

Recommended Answers

All 2 Replies

In this example it's all about order of execution. Line will have to call Multiply() to make the output string and since your function echo'd something then your example shall echo the mulitiple first then your line 14 text is output.

I see no mystery here at all.

change your function to return the value instead of echo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.