PHP Random Array without Repeat
In PHP, to generate a random array without repeating elements, we can make use of the following steps:
- Create an array with the desired elements.
- Use the shuffle() function to shuffle the array randomly.
- Optionally, use array_slice() function to limit the number of elements in the resulting array.
Let’s look at an example to understand this better:
In the above example, we have an array with 5 elements: “apple”, “banana”, “orange”, “grape”, and “mango”. We shuffle the array using the shuffle() function. Finally, we use the array_slice() function to extract the first 3 elements from the shuffled array. The resulting array would be randomly ordered and have no repeated elements.
The output of the above PHP code would be something like:
Array ( [0] => orange [1] => banana [2] => grape )
As you can see, the resulting array is randomly ordered and contains no repeated elements. You can adjust the number of elements in the output by changing the second and third parameters of the array_slice() function.