0

Modifying my chat website and I want to add a random assortment of prefixes when people join. right not the php code is: define("ANONYMOUS_PREFIX", "user"); which outputs as: user9367 joined.

Here's what I want done, but I have no hope with php.

define("ANONYMOUS_PREFIX", "$array"); 
$array = array(Mrs., Mr., Ms., Prof., Dr., Gen., Rep., Sen., St.);

Not to mention making it randomize.

anothermh
  • 9,815
  • 3
  • 33
  • 52

4 Answers4

2

Use array_rand()

$array = array('Mrs.', 'Mr.', 'Ms.', 'Prof.', 'Dr.', 'Gen.', 'Rep.', 'Sen.', 'St');
$prefix = $array[array_rand($array)];
define ("ANONYMOUS_PREFIX", $prefix);
var_dump(ANONYMOUS_PREFIX);

Note that you can only assign scalar values to constants.

Vlad Preda
  • 9,780
  • 7
  • 36
  • 63
1

Guess you're more of a user of your chat software than a programmer I'll suggest you simply replace the define with this one line:

define("ANONYMOUS_PREFIX", array_rand(array_flip(array("Dr", "Mr", "Ms", "Prof")))); 

If you want to add more prefixes always write them in brackets and add a comma before.

nedt
  • 332
  • 3
  • 15
0

A constant cannot store an array you need to use a regular variable. For randomizing use the function shuffle():

$array = array(Mrs., Mr., Ms., Prof., Dr., Gen., Rep., Sen., St.);
shuffle($array);

// you can assign the first element to the constant if you need to:
define('PREFIX', $array[0]);
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You can use mt_rand() to find a random index in your prefixes array and then define that prefix. I figure it is faster to find one random number than to randomly shuffle an array, especially considering the fact said this array might become bigger over time.

<?php
$prefixes = array(Mrs., Mr., Ms., Prof., Dr., Gen., Rep., Sen., St.);
mt_srand(microtime());
$randval = mt_rand(0,count($prefixes));
$prefix = $prefixes[$randval];
define("ANONYMOUS_PREFIX", $prefix);
Andresch Serj
  • 35,217
  • 15
  • 59
  • 101