Baldrick
Baldrick

Reputation: 11002

php wait for function

This is some example PHP code code;

<?php
function myFunc() {
    echo "blue";
}

for ($i=1;$i<=5;$i++) {
    echo "I like the colour " . myFunc() . "</br>";
}
?>

This generates the output;

blueI like the colour 
blueI like the colour 
blueI like the colour 
blueI like the colour 
blueI like the colour

In my actual project, myFunc is making an MySQL call (if it makes any difference mentioning that). How can I make my loop wait for that function to return before carrying on otherwise the output is out of order like above.

Upvotes: 1

Views: 4617

Answers (6)

fdaines
fdaines

Reputation: 1236

this is not your problem, your problem is that you have two actions.

you are concatenating a string
you are calling a function.

The result string is the contcatenation between "I like the colour " . myFunc() . "", but before you can concatenate these values, you must execute myFunc().

When you execute myFunc, you are writing "blue" to the output.

then, the result are (for every line).

blueI like the colour
(first, evaluate myFunc() an then concatenate the return value (void) to the static string.

maybe you want to do that:

<?php    
function myFunc() {
        return "blue";
    }
for ($i=1;$i<=5;$i++) {
    echo "I like the colour " . myFunc() . "</br>";
}

?>

Upvotes: 1

MattF
MattF

Reputation: 65

  <?php
  function myFunc() {
      return "blue";
  }

  for ($i=1;$i<=5;$i++) {
      $color = myFunc();
      echo "I like the colour " . $color . "</br>";
  }
  ?>

Upvotes: 1

Pangolin
Pangolin

Reputation: 7444

Try changing the the code to this:

<?php
function myFunc() {
    return "blue";
}

for ($i=1;$i<=5;$i++) {
    echo "I like the colour " . myFunc() . "</br>";
}
?>

Take note the return rather than echo.

Upvotes: 3

deepwell
deepwell

Reputation: 20851

Use the return statement:

 <?php
 function myFunc() {
     return "blue";
 }

Upvotes: 1

zsalzbank
zsalzbank

Reputation: 9857

You do not want to use echo in your function. Use return instead.

When you evalute the loop, the function is evaluated first to see if there is a return value to put into the string. Since you call echo and not return, the echo from the function is happening and then the echo from the loop is happening.

Upvotes: 2

Brad
Brad

Reputation: 163272

The problem is that myFunc() is evaluated before concatenating. Return the value from myFunc() and use that in your loop, rather than echoing in myFunc().

Upvotes: 3

Related Questions