0

How can i pull random name from the Array?

...
$all = "$a1$b1$c1$d1$e1";
$all = print_r(explode("<br>",$all));
echo $all;

----
Array ( [0] => lizzy [1] => rony [2] => )

I need random text to appear in echo

4
  • 1
    Google is your friend. secure.php.net/manual/en/function.array-rand.php Commented Mar 19, 2018 at 16:04
  • @castis yes, still need help. Commented Mar 19, 2018 at 16:05
  • I think you need to take a few steps back. What is going on with the $a1/$b1/etc variables? Why are you concatenating them and then exploding the resulting string on <br> tags? Why are you assigning the result of a call to print_r and then echo-ing it? This looks like the code you end up with after trying lots of things and not removing them when they don't work. Commented Mar 19, 2018 at 16:07
  • @iainn The full code is a bit complex, each letter has a different name. Then I separated them with br. And now I need to pull from the array a random name every time Commented Mar 19, 2018 at 16:12

2 Answers 2

3
echo $input[array_rand($all)];

This gets a random index in the array and then echos the value.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I tried it earlier. But it does not pull random name. " array_rand() expects parameter 1 to be array, boolean given in"
So that would mean there is something wrong with how you've setup the $all variable. Can you post the var_dump or print_r of that variable after the explode is called?
2

Get random characters:

rand_chars("ABCEDFG", 10); // Output: GABGFFGCDA 

Get random number:

echo rand(1, 10000); // Output: 5482

If you want to have a random string based on given input:

$chars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$clen   = strlen( $chars )-1;
$id  = '';
$length = 10;

for ($i = 0; $i < $length; $i++) 
{
     $id .= $chars[mt_rand(0,$clen)];
}

echo ($id); // Output: Gzt6syUS8M

Documentation: http://php.net/manual/en/function.rand.php

Comments