0

I was wondering if the code below was the most efficient use of session variables in PHP.

<?
session_start();
if (!isset($_SESSION['count']) || !isset($_SESSION['randomArray'])) {
  $count = 0;
  $randomArray = array();
  $sql="SELECT youtubeurl FROM Foodlist";
  $result=mysql_query($sql);
  while($row=mysql_fetch_array($result)){
       array_push($randomArray,$row['youtubeurl']);
  }
  shuffle($randomArray);
  $_SESSION['randomArray'] = $randomArray;
  $_SESSION['count'] = $count; 
} elseif ($_SESSION['count'] >= sizeof($_SESSION['randomArray'])){
  $_SESSION['count'] = 0;
  $randomArray = $_SESSION['randomArray'];
  shuffle($randomArray);
  $_SESSION['randomArray'] = $randomArray;
} else{
  $randomArray = $_SESSION['randomArray'];
  $count = $_SESSION['count'];
  echo $randomArray[$count];
  $_SESSION['count']++;
}
?>

The intent of the code should be obvious, if I did it correctly. But basically there exists an list(randomArray) of strings which is looped through once. After each complete pass, the list is shuffled. Every element prints out once before any single element is printed out twice.

So, is this the most efficient way of doing this?

1 Answer 1

1

I'd simplify this as follows:

if (empty($_SESSION['randomList'])) {
    $result = mysql_query("SELECT youtubeurl FROM Foodlist"); // or die(mysql_error())
    while ($row = mysql_fetch_assoc($result)) {
       $_SESSION['randomList'][] = $row['youtubeurl'];
    }
    shuffle($_SESSION['randomList']);
}

echo array_shift($_SESSION['randomList']);
Sign up to request clarification or add additional context in comments.

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.