-2

I have a string:

$string = '0';

And in an echo statement like this:

echo ($string ? 'true':'false');

I want the '0' to be true. It currently is false.

Is there a way to adjust the echo statement? I know I can for example add a space in the string:

$string = ' 0';

And it will be true. But I am hoping for a solution that doesn't require me adjusting the string.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

1

Is there a way to adjust the echo statement?

No - not without editing PHP's source code and rebuilding it yourself. The echo statement in PHP has 20-year-old well-documented behaviour - it would be foolish to make your PHP environment incompatible with the rest of the PHP ecosystem just to save yourself a few keystrokes.

A better idea is just to add your own global function:

<?php

function zeroToBoolText( $str ) {
    if( !is_string( $str ) ) die( "Argument is not a string." );
    if( $str === '0' ) {
        return 'true';
    }
    else {
        return ( $str ? 'true' : 'false' );
    }
}

?>

Used like so:

$string = '0';

echo zeroToBoolText( $string );
Dai
  • 141,631
  • 28
  • 261
  • 374
0

Using the below condition you can change if string is 0 true..

    if($string === '0')
    {
        $string = true;
    }
    else
    {
        $string = false;
    }

Try it, i think you need this one thank you..

Eibs
  • 86
  • 8
  • It's important to use the exactly-equal-to operator `===` instead of the approximately-equal-to operator `==` in PHP - otherwise your posted code won't work the way OP wants it to. – Dai Aug 21 '20 at 09:51
  • Just replace that exact-equal-to operator, it will return a correct result : - ) – Eibs Aug 21 '20 at 09:53