Category: 1semE14

  • PHP: Cookie, Array, Loop

    A cookie is saved locally. Therefore different browsers will display whatever the user has saved. At least as long as the cookie is alive.
    A cookie is saved locally. Therefore different browsers will display whatever the user has saved. At least as long as the cookie is “alive”.

    The complete code to this article is available here.

    We use cookies in order to save information about or from the user input. If you compare my Firefox and Chrome browsers they will format the Microlite roleplaying web page according to random values, dates and saved input. Computergames use random values in stead of dice. First the character is saved in an associative array.

    // ASSOCIATIVE ARRAY
    // Define the character array.
    // “key” => value
    $character = array(
    “strength” => rand(3,18),
    “dexterity” => rand(3,18),
    “mind” => rand(3,18),
    “charisma” => rand(3,18),
    “class” => $class[rand(0, $classes)],
    “race” => $race[rand(0, $races)],
    “address” => “Shire”,
    “hitpoints” => rand(3,18),
    “level” => 1,
    );

    Above you see the method in action. rand(3,18) is an imitation of the role playing “3d6” (throw 3 sixsided dices). The random generator will give a value between 3 and 18. If you read the rules of Microlite 84 it’s easy to add more character properties.

    The cookie

    In this case we’ll save the character data in a cookie in the client browser. However a cookie can only store a string. PHP can convert an array to a string:

    $toCookie = serialize($character);

    Now we can save the data in a cookie via setcookie:

    setcookie(“character”, $toCookie, time()+ (60 * 60 * 60 * 24));

    After the cookie has been set PHP can use the data. That is next time the page is read. PHP can check whether the cookie exists by isset($var):

    if(isset( $_COOKIE[“character”] ) ) {

    $charUnSer = unserialize($_COOKIE[“character”]); 

    }

    This will convert the cookie string to an array.

    The Loop

    In order to echo or print the values of the array to a table:

    foreach ($charUnSer as $key => $value)
    {
    print ”
    <tr>
    <td> $key </td> <td> $value </td>
    </tr>
    “;
    }

    And this loop will then create the character table in the wbbage.

Enable Notifications OK No thanks

We use cookies - more information

Multimusen.dk will set a few cookies from Doubleclick, Google and the Social Media plugins they ay set some cookies. Some of my pages use APIs - such as YouTube, LinkedIn, Google Fonts, Google Maps, Mapbox, Spotify, Jetpack, Twitter, Facebook &c.. Such plugins may set the odd cookie.

Close