views:

31

answers:

3

Hello,

I'm creating a humble web browser-game in PHP. I'm making a "robbery" section... I want to greet the user if he succeeds at a robbery. Some messages like "You're the man!", "A piece of cake, it was" etc.

I want more than, like, 5 different messages/notifications like this. How could I do this? how could I pick them from a .txt file, or have them imported from another PHP page which has these messages stored in variables to the "robbery" page...

Please, if you can provide a useful snippet of code, like a function for picking random messages, etc, that would be great.

Also if you can use OOP... :)

Thank you very much in advance...

A: 

I don't see a specific need for an object here, just a function...

function message(){
$mes = array("Message 1","Message 2","Message 3","Message 4");
shuffle($mes);
return $mes[0];
}

That will give you a random message from one of the ones you put in the array. You could make as many messages as you like.

Or...

You could do an include file like you asked. I would again store them in an array in the include file then return a random message.

messages.php:

$mes = array("Message 1","Message 2","Message 3","Message 4");

index.php

include('messages.php');//be sure to include path to messages.php
shuffle($mes);
echo $mes[0];//will echo a random message
Capt Otis
+1  A: 

This is a function that accepts a string (the filename) and reads the messages from it. It then returns the messages as an array so you can use them in your app.

<?php
function loadMessagesFromFile($file)
{
    if(!file_exists($file))
    {
        return false;
    }

    $fh       = fopen($file, 'r');
    $messages = array();

    while($data = fgets($fh))
    {
        $messages[] = $data;
    }

    fclose($fh);

    return $messages;
}

$messages_from_file = loadMessagesFromFile('messages.txt');
$key = array_rand($messages_from_file);
echo $messages_from_file[$key];

Another option is storing the messages in PHP:

<?php
$messages = array('message', 'another message');
$key = array_rand($messages);
echo $messages[$key];
Evert
Keep in mind that array_rand() returns the key/index of the array, not the value. You still need to look it up in the array.
Fanis
Thanks! I fixed it.
Evert
A: 

Put your messages into a file, one message per line, and then you can load that file into an array using file. The FILE_IGNORE_NEW_LINES flag will strip the newline from the end of each element in the returned array. Then you can shuffle the array to randomize it.

$messages = file('messages.txt', FILE_IGNORE_NEW_LINES);
shuffle($messages);
$message = $message[0]; // get the first of the shuffled $messages
Daniel Vandersluis