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";
    }
2
  • You have it almost ok. Just after echo-ing the value, you have to unset it from array. Commented Apr 19, 2017 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]; Commented Apr 19, 2017 at 13:22

2 Answers 2

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

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

2 Comments

Not to take too much of your time. but what gives me the then allowed to make include '' 2.php "; instead of echo" 2.php "?
You can use variable string as file name. include $el;
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.