Jump to content

Ternary operator with multiple if/else if


Mad_Griffith

Recommended Posts

Hi, I am building a basic routing system and I am now trying to get the ternary operator equivalent of:

if( $explodedUriCount === 1 ) {
    echo $pageName;
} else if (explodedUriCount === 3) {
    echo $pageType;
} else {
    echo '404';
}

What would it be?

 

Thank you.

Edited by Mad_Griffith
Link to comment
Share on other sites

I don't see this approach as being a more readable or maintainable alternative, but here goes

$value = $explodedUriCount === 1 ? $pageName : $explodedUriCount === 3 ? $pageType : '404';
Link to comment
Share on other sites

Hi,

this would be the final one, but it does not work:

$pageChoice = $uriCount === 1 ? $pageName : $uriCount === 3 ? $pageType : '404';

require( 'pages/' . $pageChoice . '.php' );

I managed to have the ternary partially work with this syntax:

( $uriCount === 1 ? $pageName : ( $uriCount === 3 ? $pageType : '404' ) )

I said "partially", because the else clause still does not trigger :\

Link to comment
Share on other sites

Test it with

        <?php
        $explodedUriCount = 3;

        $pageName = "pagename";
        $pageType = "pagetype";

        $pageChoice = $explodedUriCount === 1 ? $pageName : ($explodedUriCount === 3 ? $pageType : '404');

        echo ( 'pages/' . $pageChoice . '.php' );
        ?>

It should work, adjust initial value of $explodedUriCount to see result

Edited by dsonesuk
Link to comment
Share on other sites

Thank you. Following your advice, I realised I had to apply a more general condition for the 404 error to trigger properly, so this ended up bein the final code:

require( 'pages/' . (!in_array($pageName, $pageNames) && $pageName !== 'home'? '404' : ( $uriCount === 1 ? $pageName : ( $uriCount === 3 ? $pageType : '' ) )) . '.php' );
Edited by Mad_Griffith
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...