Conditional Includes?

I want to use a conditional statement to determine which include should be used based on whether the statement evaluates true or false. I think it’s a matter of syntax but I haven’t figured out the correct form. It seems to get more complicated with variables inside the includes.

Example:

<? if($issue_number=="n") {
echo "<?php include 'issues/'."$nl_issue[$nl-1]".'.php'; ?>";
} else {
echo <?php include 'issues/'."$nl_issue[$issue_number]".'.php'; ?>";
}
?>

Thanks Rajug - I hadn’t considered that because I’m passing the variable in the URL based on the link selected on the previous page; so technically there’s no user created values - but I’ve edited those URLs myself, so it’s a condition that should be included.

This isn’t the best approach. If the file is not found, then a Fatal Error would be thrown and the page will not render.

As said above you can use file_exists function to first check if the file exists, even if you created the URL.

Instead of checking whether or not the file exists, simply use require(), or if there are any function/class declarations in the file, use require_once(). That will fail if the file is not found or can’t be opened.

How about this?


<?php
if($issue_number == "n") {
    $issue_page = $nl_issue[$nl - 1];
} else {
    $issue_page = $nl_issue[$issue_number];
}
include 'issues/'. $issue_page . '.php';
?>

I fail to see how missing some portion of site functionality and breaking in a way in which it isn’t immediately obvious that there’s an issue to everyone involved is better than throwing a fatal error.

If an included file isn’t required, why is it there? At what point during development have you ever said “Well, this would be nice to have, but it’s not a big deal if it doesn’t show up”? That kind of thinking leads to unpredictable behavior, along which road more critical errors (and usually less obvious ones) lie.

I would check if file exists for sure as well:


if(file_exists('issues/'. $issue_page . '.php'))
    include 'issues/'. $issue_page . '.php';
else
    // throw some error message or do something else

Hey pmw57 - good solution. One to grow on for a newbie like myself.