Jump to content

[SOLVED] Question regarding sessions


Michdd

Recommended Posts

On some popular tutorial sites I've seen something like this as an example for using a session:

 

<?php
session_start();  
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+ 1;
else
    $_SESSION['views'] = 1;

echo "views = ". $_SESSION['views']; 
?>

 

Does that mean with sessions you can't use { } For example would this be the same?

 

<?php
session_start();  
if(isset($_SESSION['views'])) {
    $_SESSION['views'] = $_SESSION['views']+ 1;
} else {
    $_SESSION['views'] = 1;
}
echo "views = ". $_SESSION['views']; 
?>

Link to comment
https://forums.phpfreaks.com/topic/131991-solved-question-regarding-sessions/
Share on other sites

It's the same, yes, but it has nothing to do with sessions. You aren't required to use braces - {} - in a while/if/etc statement if the contained statement is only one statement long. Braces are actually seen as grouping multiple statements into one statement.

 

if(condition)
   statement;
else
   statement;

for(condition) statement;

is equivalent in all cases to

if(condition) {
   statement;
} else {
   statement;
}

for(condition) { statement; }

but you can not do, for instance...

if(condition)
   statement 1;
   statement 2;
else
   statement 1;
   statement 2;

because this is two statements, you must group them into 1 with braces

if(condition) {
   statement 1;
   statement 2;
} else {
   statement 1;
   statement 2;
}

 

I always use braces because it makes debugging easier (I can stick things into if statements without worrying about statement counts), and because it seems easier to read to me... but that's just my personal choice.

Thanks, I think I'll stick to using braces, because I'm used to it, and as you said, it's easier to debug. I do have one more question about sessions. Because I haven't used them before. If I start a session so I have to put session_start(); on the begging on every page? Or if it's on say index.php do I have to put it on somepage.php or will it be passed automatically?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.