WordPress.org

Support

Support » Miscellaneous » General PHP Help — If Statements

General PHP Help — If Statements

  • Can someone please help me with a general PHP question? (While this is not directly related to wordpress you guys have been a great help sofar so I have decided to ask here)

    I have a line of code that states:


    define('TEMPLATE_FILE', 'template.php');

    What I would like to do instead is include an if statment so IF “template.php” exists it will use it. If it does not exist I would like the script to defult to “template.html”

    Any sugestions on how to do this?

Viewing 5 replies - 1 through 5 (of 5 total)
  • I was kind of thinking something like


    <?php
    $filepath = 'if (file_exists(template.php))
    {return template.php;}
    else {return template.html;}';
    define('TEMPLATE_FILE', '$filepath');
    ?>

    would something like that work?

    If it would I string multiple ones of those together? (.php –> .html –> .asp –> .xml)? If you understand what I mean

    You can use what’s called a ternary operator to test and provide the correct template to $filepath:

    <?php
    $filepath = (file_exists('template.php')) ? 'template.php' : 'template.html';
    define(TEMPLATE_FILE, $filepath);
    ?>

    This evaluates the condition of file_exists(template.php) — if it exists (true) $filepath takes it as the value; if not (false), template.html is assigned.

    You’ll have to explain your second question in a little more detail.

    Thanks Kafkaesqui I will try out that code. I am curently trying to learn PHP so I will also take a look at ternary operators. Thanks for your time.

    The second question was if the script cannot find template.php OR template.html it will defult to template.asp or something like that, stringing multiple IFs together.

    Cron

    RE: The second question, you could try something like:

    <?php
    $exts = array('php', 'html', 'asp', 'xml');
    foreach($exts as $ext) {
    $filepath = 'template.' . $ext;
    if(file_exists($filepath)) {
    define('TEMPLATE_FILE', $filepath);
    return;
    }
    }
    ?>

    Thanks a ton for the help Kafkaesqui. You saved me hours, literly. Now that I know about ternary operators my code will be much cleaner from here on (less {}s and elses and stuff).

    Thanks for your help,

    Cron

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘General PHP Help — If Statements’ is closed to new replies.
Skip to toolbar