0

I have a simple problem that I want to make some code where it is not possible for it to print two identical variables like:

2.php
2.php
3.php

it should only mix them instead as the 3 files change location every time but does not repeat itself.

a correct answer is:

4.php
2.php
3.php

and

3.php
4.php
2.php

The code looks like this:

<?php


$first = '2.php';
$second = '3.php';
$third = '4.php';

    $array = array($first, $second, $third);
    for ($i=0; $i<3; $i++) {
    echo $array[rand(0, count($array) - 1)] . "\n";
    }
Jen R
  • 1,527
  • 18
  • 23
  • You have it almost ok. Just after echo-ing the value, you have to unset it from array. – Autista_z Apr 19 '17 at 13:21
  • Unset each element after it's displayed. If you need to preserve the initial array, copy it first. Also, you should start using the array shorthand: `$array = [$first, $second, $third];` – alanlittle Apr 19 '17 at 13:22

2 Answers2

2

You can use shuffle() function for that:

$first = '2.php';
$second = '3.php';
$third = '4.php';

$array = array($first, $second, $third);
shuffle($array);

foreach($array as $el) {
    echo $el . PHP_EOL;
}

Here's working code: https://3v4l.org/V2GTk

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
0

I am not sure i understand what you are trying to accomplish but if i did understand, you need to print 3 different numbers without repeating any of them. In the end of each output, add ".php" extension.

$existing_numbers = [];

while( count( $existing_numbers ) < 2 ) { // Loop until we get 3 unique values
  $random_number = rand(0, 9);
  array_push( $existing_numbers, $random_number . '.php' );
  array_unique( $existing_numbers ); // Remove duplications from array
}

This code haven't been tested yet but the login should be good.