exam

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lenticchia
Forum Newbie
Posts: 1
Joined: Sun Jan 16, 2011 5:37 am

exam

Post 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];
?>
Last edited by Benjamin on Mon Jan 17, 2011 3:05 am, edited 1 time in total.
Reason: Added [syntax=php] tags.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: exam

Post 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];

?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: exam

Post 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)
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: exam

Post 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.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply