Page 1 of 1

exam

Posted: Sun Jan 16, 2011 5:47 am
by lenticchia
Hi everybody, I'm Daniele.

I have a PHP exam tomorrow :(

I don't understand a part of code. it's very short, could someone explain me what the program does at each step please?

many many thanks

Code: Select all

<?php
$fruit = array (0=>'banana',
1=>'arancia',
2=>'limone',
3=>'pesca');
session_start();
if (!isset($_SESSION['count'])) {
$count = 0;
} else {
$count=$_SESSION['count']++ % 4;
}
$_SESSION['count'] = $count;
echo $fruit[$count];
?>

Re: exam

Posted: Sun Jan 16, 2011 9:23 am
by social_experiment

Code: Select all

<?php
// create an array called 'fruit' (with 4 elements)
$fruit = array (0=>'banana',
1=>'arancia',
2=>'limone',
3=>'pesca');
// start a session , IRL this will give an error because
// session_start() needs to be called before anything
// else
session_start();
// if the session variable $_SESSION['count'] is not set,
// the $count variable is assigned a value of 0
if (!isset($_SESSION['count'])) {
$count = 0;
// if the session variable is set, increment it by 1.
// no idea on the % symbol.
} else {
$count=$_SESSION['count']++ % 4;
}
// assign the value of the $count variable to the session 
// variable $_SESSION['count']
$_SESSION['count'] = $count;
// display the element from the array that has the index 
// value of $count
echo $fruit[$count];

?>

Re: exam

Posted: Sun Jan 16, 2011 11:20 am
by John Cartwright
The % symbol is the modulos operator. It returns the remainder of the divisor. I.e., 10 % 4 = 2 (4+4 = 8 .. with 2 remainder)

Re: exam

Posted: Sun Jan 16, 2011 11:46 pm
by social_experiment
John Cartwright wrote:The % symbol is the modulos operator.
Ah ok, i thought it was something like that but i wasn't certain about it.