2

I am trying to get random array:

for example:

$navItems= array(

    array(
        slug    => "top10.php",
        title   => "Top 10 geriausi"
    ),
    array(
        slug    => "index.php",
        title   => "Pagrindinis"
    ),
    array(
        slug    => "top-prasciausi.php",
        title   => "Top 10 prasciausi"
    ),
    array(
        slug    => "visi-politikai.php",
        title   => "Visi politiki"
    ),
);

and after that use this random array inside foreach loop like this:

foreach ($navItems as $item) {
    echo "<li class=\"hov\"><a href=\"$item[slug]\">$item[title]</a><li>";
}

Instead of $navItems variable i want to use that random arrays from $navItems array

1 Answer 1

2

You can use shuffle to randomize the array

Note: If you are trying to pick one from the array, you can use shuffle and select the first element of the array.

$navItems = array(
  array(
        'slug'    => "top10.php",
        'title'   => "Top 10 geriausi"
  ),
  array(
        'slug'    => "index.php",
        'title'   => "Pagrindinis"
  ),
  array(
        'slug'    => "top-prasciausi.php",
        'title'   => "Top 10 prasciausi"
  ),
  array(
        'slug'    => "visi-politikai.php",
        'title'   => "Visi politiki"
  ),
);

shuffle( $navItems );

echo "<pre>";
print_r( $navItems );
echo "</pre>";

This will result to something like:

Array
(
    [0] => Array
        (
            [slug] => index.php
            [title] => Pagrindinis
        )

    [1] => Array
        (
            [slug] => visi-politikai.php
            [title] => Visi politiki
        )

    [2] => Array
        (
            [slug] => top10.php
            [title] => Top 10 geriausi
        )

    [3] => Array
        (
            [slug] => top-prasciausi.php
            [title] => Top 10 prasciausi
        )

)

Doc: shuffle

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

2 Comments

Thank you that works, I made mistake trying to shuffle it in foreach loop :)
Happy to help @JonasTamoševičius

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.