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
https://forums.phpfreaks.com/topic/223229-random-string-noob-question-p/
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>

..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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.