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

  • 1
    Google is your friend. https://secure.php.net/manual/en/function.array-rand.php – castis Mar 19 '18 at 16:04
  • @castis yes, still need help. –  Mar 19 '18 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 `
    ` 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.
    – iainn Mar 19 '18 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 –  Mar 19 '18 at 16:12

2 Answers2

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

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

dukedevil294
  • 1,285
  • 17
  • 31
  • Yes, I tried it earlier. But it does not pull random name. " array_rand() expects parameter 1 to be array, boolean given in" –  Mar 19 '18 at 16:16
  • 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? – dukedevil294 Mar 19 '18 at 16:19
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

Ronnie Oosting
  • 1,252
  • 2
  • 14
  • 35