Generate a word between defined words [PHP]

Asked

Viewed 2,945 times

1

I’m pretty new at PHP, but I already know the basics of HTML, and a large part of Ruby script (nay ruby on rails).

Well, you know, how can I generate a word or something random, you might say, but not so random. As if to generate a word from a "database". For example:

I define in my code two words: Parlance, Tongue and Lang.
I want to make php generate one of them, but not generate something like language, or anything other than Parlance, Tongue or Lang.

  • You have a list of words and want to choose one randomly?

  • exactly. That’s what I need

2 answers

3

You can do it like this:

$palavras = array('Linguagem', 'Língua', 'Lang');
$aleatorio = rand(0, 2);
echo $palavras[$aleatorio];

Example: https://ideone.com/ZvMkec

Define an array with the words you want to use, and then the rand() to generate a random number. The method rand() lets you specify the minimum and maximum number, notice that I used 0 and 2 because arrays Intel starts at zero.

You can just do $aleatorio = rand(0, count($palavras) - 1); and is independent of the array’s number of elements.

Example using rand(0, count($palavras) - 1); and a function: https://ideone.com/TfQMa5

  • 1

    Perfect, thank you very much, solved my question!

  • I would still use count($palavras)-1 as the maximum value of rand()

  • 1

    @Diogodoreto well seen, I put it just before your comment, and it will be count($palavras) -1.

  • 1

    Yeah, I saw it the moment I posted ;)

1

Can use shuffle to shuffle the array and use current to return the first element.

$array = array( 'Linguagem', 'Língua', 'Lang' );

shuffle( $array );
echo current( $array );

Example

  • 1

    If the array is large, you will have performance problems with this method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.