Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Random Number Generator Using Array and substr

Tags:

php

I'm trying to build a simple lottery number generator for my own amusement. I have to pick six numbers between 1 & 49, obviously without repeats.

I have tried using the mt_rand feature for six different variables then echoing them in order, but I guess there is the possibility of repeated numbers. So now I'm trying to get the following to work.

<?php 
$randomString = substr(shuffle("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49"), 0, 6); echo $randomString; 
?>

I know that substr is for strings and not arrays but I can't find the alternative.

Anyone got a solution?

like image 592
Jonathan Rosenfeld Avatar asked Aug 19 '26 14:08

Jonathan Rosenfeld


1 Answers

You can use array_slice to get 6 numbers from the array:

<?php
$numbers = range(1, 49);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 6);
print_r($numbers);
?>
like image 101
jh314 Avatar answered Aug 22 '26 05:08

jh314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!