Jump to content

Random string? (Noob question :P)


DarkHylian

Recommended Posts

Hi everyone

 

Well I've started learning php yesterday and now I encountered my first problem, I looked around but I don't really know what to search for if I want my answer so here  I come :D

 

<html>
<body>
<?php
$names = array('Peter','Quagmire','Joe');
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$who = rand(0,2);
$who2 = $names[$who];
echo "$names[$who] is $ages[$who2] years old";
?>
</body>
</html>

 

This is the script I have, and there is the kind of script I expected:

 

<html>
<body>
<?php
$names = array('Peter','Quagmire','Joe');
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$who = rand('Peter','Quagmire','Joe');
echo "$who is $ages[$who] years old";
?>
</body>
</html>

 

But after some search I concluded that rand is only used for random numbers

 

So, my question is, which function should I use to achieve my goal? Is there any randstring('string1','string2',etc) command?

 

Tnx for your time

 

Link to comment
Share on other sites

Hi, and welcome to programming in PHP.

 

You're going to want to do something more like this:

<html>
<body>
<?php
$characters = array('Peter'=>32,'Quagmire'=>30,'Joe'=>34);
$rand_character = array_rand($characters);
echo "$rand_character is $characters[$rand_character] years old";
?>
</body>
</html>

Link to comment
Share on other sites

..and for flexibility you might want to do it this way:

 

$characters = array(

  array('name'=>'Peter', 'age'=>32),
  array('name'=>'Quagmire', 'age'=>30),
  array('name'=>'Joe', 'age'=>34)

);

$who = $characters[rand(0, count($characters)-1)];

echo $who['name'] . ' is ' . $who['age'] . ' years old';

 

That way you can easily add new information to each character without conflicting with the key=>index structure of the array.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.