0

I want to include 2 files based on the following conditional statement

<?php 
 if (isset($_SESSION['name']) && $_SESSION['name'] == true) { 
 include 'file_a.php'; 
 }else{ 
 include 'file_b.php';
 }
 ?>

Is this the correct way?

4
  • 1
    this should help stackoverflow Commented May 11, 2014 at 12:25
  • If you are getting what you want, then there is nothing wrong with this method, I think. Commented May 11, 2014 at 12:25
  • You can also use ternary operator to change in single line statment Commented May 11, 2014 at 12:25
  • Using ternary operation in this case won't be rather good choice. It would make code illegible Commented May 11, 2014 at 12:37

2 Answers 2

1

You can try next code:

if(session_id() == '') {
   session_start();
   include !empty($_SESSION['name']) ? 'file_a.php' : 'file_b.php';
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know why these conditional satements aren't following the logic. I used mysql num rows to compare and call the include files seperately. Howeve I shall get it working. Thannks,
1

It depends what you mean by 'correct':

If you mean 'is it valid' then yes, your code will work and there are no syntax errors.

If you mean 'can it be prettier', then perhaps it could, but it's personal preference whether you'd want to use ternary operators or not:

$toShow = isset($_SESSION['name']) && $_SESSION['name'] ? "file_a.php" : "file_b.php";
include $toShow;

Again, whether or not this is better or worse than your previous code, is down to your personal opinion.

TL;DR: Yes, your code is correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.