Paul
Paul

Reputation: 6176

php modulo and print_r of the result?

i wanted to make my own quarter-final draw for the champion's league (tomorrow, friday 16 of march) : i've got 2 questions : first the modulo does not work : it shows "another match" after every entry in the array, whereas i wanted it to be written every two matches (every 2 entries)...

Second question : is there a better way to "print" the result? like a print_r without the index and where i could say "add \n after each entry" ?

<body>
<?php 

$array = array("real", "barça", "bayern",  "apoel",  "chelsea",  "milan",  "benfica",  "marseille" );

$new = array();
$incr = count($array);

while($incr>0){
    $random = rand(0, count($array));

    if (!in_array($array[$random], $new)){
        $new[] = $array[$random];
        if ( (count($new) % 2) ){
            $new[] = " -- another match : ";
        }
        $incr--;
    }   
}

print_r($new);


?>
<p>results</p>
</body>

Thanks for your help

Upvotes: 1

Views: 261

Answers (3)

Ciaran
Ciaran

Reputation: 2184

Another option would be to shuffle the array then just pop off each of the elements

$array = array("real", "barça", "bayern",  "apoel",  "chelsea",  "milan",  "benfica",  "marseille" );

shuffle($array);

while($a = array_pop($array)) {
    echo $a." vs. ".array_pop($array)." <br />";
}

Sample output:

apoel vs. real 
barça vs. milan 
marseille vs. bayern 
chelsea vs. benfica

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212452

The modulus is working exactly as you're telling it to.

(count($new) % 2) ){

when count($new) = 1, 1 % 2 = 1, = true
when count($new) = 2, 2 % 2 = 0, = false
when count($new) = 3, 3 % 2 = 1, = true
when count($new) = 4, 4 % 2 = 0, = false
when count($new) = 5, 5 % 2 = 1, = true
when count($new) = 6, 6 % 2 = 0, = false

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324730

The modulo is working perfectly:

  • The array starts empty.
  • You add an element to it.
  • The length is 1, so 1 % 2, so 1, so truthy, so you add -- another match to the array
  • So the length is now 2
  • Next iteration of the loop, you add another element to the array.
  • The length is now 3, so 3 % 2, so 1, so truthy, so you add -- another match

And so on. Whatever it is you're trying to do, it's not what you told the server to do.

What you should probably do is something like this:

$array = Array(........);
while($a = array_shift($array)) {
    $random = rand(0,count($array)-1); // -1 is important!
    echo $a." vs. ".$array[$random]."<br />";
    unset($array[$random)];
    // no need to realign keys since array_shift already does that
}

Upvotes: 1

Related Questions