Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Help with Array inside Loop

Featured Replies

I'm cutting out loads of the code here but this should give you a good enough idea..

 

<?php
while($row = mysql_fetch_array($result))

{
//Example URL//  $url = "http://youtube.com/watch?v=abc123";
parse_str($url["query"]);
// ^ Generates $v variable//


$shuffle = array();//Set Shuffle Array//
array_push($shuffle,$v);  //Add Video ID to Shuffle Array//

}

$rand = array_rand($shuffle, 1);

echo "Random Video ID = " . $shuffle[$rand];    ?>

 

Basically what I want to do is get every $v variable and add it to the $shuffle array so I can pick out random values, but when I try this it only seems to add the last $v that was set :unsure:

 

Thanks @jamesrwhite

A quick glance would make me believe you don't want to re-assign the $shuffle array each time inside the loop. This is basically clearing out the array on each iteration before adding that iteration's $v to the (new) array. Hence by the time the loop finishes, only the last $v has been added (to the new and empty array that was created in that iteration). If you see what I mean?!

 

Anyway, to fix it, delete the line:

 

$shuffle = array();

and place it instead before and outside the loop, like this:

 

$shuffle = array();
while($row = mysql_fetch_array($result))

 

Does that solve (and importantly explain) it for you?

  • Author

Ahh yh It seems so obvious now..

 

Thanks :)

array_push isn't really intended for single items to be added to an array

you'd be better off using

$shuffle[] = $v; //Add Video ID to Shuffle Array//

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.