I'm trying to create a php script to print fibonaaci series. The idea is to add a new number to the series everytime the page is refreshed and print the series.

<?php

if (!isset($_COOKIE["fno"]))
    {setcookie("fno",0,time()+3600);}
if (!isset($_COOKIE["sno"]))
    {setcookie("sno",1,time()+3600);}
if (!isset($_COOKIE["series"]))
    {
    $text="0 1 ";
    setcookie("series",$text,time()+3600);
    }
    $fno=$_COOKIE["fno"];
    $sno=$_COOKIE["sno"];
    $fibostring=$_COOKIE["series"];
    //echo $fibostring;
    $tno=$fno+$sno;
    $fibostring.=$tno . " ";
    setcookie("fno",$sno,time()+3600);
    setcookie("sno",$tno,time()+3600);
    setcookie("series",$fibostring,time()+3600);


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Fibonacci Series</title>
</head>
<body bgcolor="#FFFFFF">
<div style="font-size:20px; color:#cc0000; margin-top:10px"><?php echo $fibostring ?></div>
</body>
</html>

Check out : din3shie.x10.mx/fibo.php
Can anybody tell me what's wrong ?

Recommended Answers

All 4 Replies

To add a new fibonacci number on each refresh you should store each previous and current value in a session.

session_start();

// on the beginning you have 0 and 1
if(!isset($_SESSION['previous']) || !isset($_SESSION['current'])) {

    $_SESSION['previous'] = 0;
    $_SESSION['current'] = 1;

    echo $_SESSION['previous'];
    echo ' ';
    echo $_SESSION['current'];

} else {

    $current = $_SESSION['previous'] + $_SESSION['current'];

    echo $current;

    $_SESSION['previous'] = $_SESSION['current'];
    $_SESSION['current'] = $current;
}
commented: Nice Answer. Better than my links! +9
Member Avatar for diafol

I doubt the OP is still awaiting an answer, but for anybody else -

Agreed - sessions would be the way to go IMO.

I have just noticed that the question is mentioning cookies. Well the principle is the same as using session.

Anyway, it was just nice to do a little brain exercise.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.