WordPress.org

Ready to get started?Download WordPress

Forums

General PHP Help -- If Statements (6 posts)

  1. cron
    Member
    Posted 8 years ago #

    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?

  2. cron
    Member
    Posted 8 years ago #

    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

  3. Kafkaesqui

    Posted 8 years ago #

    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.

  4. cron
    Member
    Posted 8 years ago #

    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

  5. Kafkaesqui

    Posted 8 years ago #

    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;
    }
    }
    ?>

  6. cron
    Member
    Posted 8 years ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.