开发者

php check if file exist, however it includes a lot of apostrophes and backslashes

开发者 https://www.devze.com 2023-02-22 14:14 出处:网络
I was wondering what you\'d do if you wanted to link to a directory index file if it existed? So far what I have is this

I was wondering what you'd do if you wanted to link to a directory index file if it existed?

So far what I have is this

$filename = './../season/6/index.php';

if (file_exists($filename)) {
   echo '<div id="lesson"> 
<a href="./../Season/6/index.php">season 6</a>
</div>';
} else {
   echo "";
}

However, what I want now is something like this

$lesson="5";
$lesson++; // (or someway to increase it) 

$filename = './../season/$lesson/index.php';

if (file_exists($filename)) {
   echo '
<a href="./../Season/$lesson/index.php">season $lesson</a>
开发者_开发知识库';
} else {
   echo "";
}

however, I know that php won't allow ALL Those backslashes in that echo or apostrophe. How can I compensate? Should I use String concatenation?


As an example:

<?php

foreach(range(1,10) as $lesson){

$filename = "./../season/$lesson/index.php";
        echo $filename;
}

?>

A live demo:

http://www.ideone.com/pemRv

Essentially two things here:

1) Use double quotes to have variable interpolation.

2) Just have $lesson be an integer, so you can increment the value.


Variable interpolation only occurs in double quoted strings, you are using single quoted.

Also, your else { ... } is unnecessary.

However, it sounds like this method could be improved. What upper bound will you go to before you stop checking? This will be a lot of unnecessary overhead.

0

精彩评论

暂无评论...
验证码 换一张
取 消