0

I have some code to generate 4 unique random numbers between 0-9: -

//Globals
$arr = array();
$gridMax = 9;
$i = 0;


while ( count($arr) < 4 ) {
$x = mt_rand(0, $gridMax);
    if ( !in_array($x, $arr) ) {
        $arr[] = $x;

        }
}

print_r($arr);

I'm trying to create a grid and if the corresponding grid number is the same as one of the 4 unique values in my array then I want it to add some text to the $build variable. If not, do nothing: -

while ($i <= $gridMax) {
foreach ($arr as $value) {
    if ($value == $i) { 
        $build = "build";
    } else {
        $build = "";
    }

}

echo "<li class=\"map\">{$build}</li>";
$i++;
}

However, it only works for the final value in the last key (shown here): -

http://www.kryptonite-dove.com/sandbox/mt_rand/

Can anyone give me some pointers? I've been absent from coding for a number of months and my mind is a little foggy!

0

2 Answers 2

1
while ($i <= $gridMax) 
{
    $build = '';
    if(in_array($i, $arr)) $build = 'build';

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This seems a lot faster, easier on the eye and more efficient so have marked as the answer. Thanks very much all.
1

What about this:

while ($i <= $gridMax) 
{
    $build = '';

    foreach ($arr as $value) 
    {
        if ($value == $i) 
        { 
            $build .= "build";
        }   
        else        
        {
            $build .= "";
        }
    }

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}

2 Comments

It works like a charm thanks! can you explain why it works like this for me?
I know, I know! Let's say $i = 3, $arr = [1,2,3,4]. In your original code for 1 and 2 it's false, for 3 the $build changes to 'build', but for 4 it changes again to ''. Here you append to $build instead of setting it.

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.