Search code examples
phpob-start

Turn php loop output to variable?


I am still learning php and this is how i convert php loop statement output to variable::

ob_start(); 
if 2 > 1 {
echo 'It is OK';
} else {
echo 'It is not OK';
}
$myvar = ob_get_clean();

echo $myvar;

Now the $myvar will output above if result, but is there better approach in doing this?


Solution

  • First, there is no looping in your code: if/else blocks are executed once, not in a loop.

    Second, if you want to save the string, you can assign it to your variable directly, using many approaches:

    if/else

    if(2 > 1) $myVar = 'it is OK';
    else      $myVar = 'it is not OK';
    

    switch case

    switch (2>1):
      case true: 
        $myVar = 'it is OK';
        break;
      default:
        $myVar = 'it is not OK';
    endswitch;
    

    ternary operator

    $myVar = 2>1 ? 'it is OK' : 'it is not OK';