0

I am very new to PHP and kinda new to HTML. I am making a website with a product of the week and have an idea but can't find out how to perform it.

My idea is to create and array with every different product and use array_rand to randomly choose one, then use a cron job to run it every Monday. I then wish for the chosen array output to be put into the href within the button for the product of the week.

Am I going about this correctly or am I being horrifically stupid?

Cheers, Fynn

FynnaT
  • 1
  • 1
  • 1
    you need some method to store the random product (e.g., a database or a text file). then you can do it. You also do not need to use a cron job. Just one page execution from a visitor will take care of it. –  Jun 27 '14 at 21:06
  • 1
    Maybe you can just get a random number based on the week (see here: http://stackoverflow.com/questions/9567673/get-week-number-in-the-year-from-a-date-php). That would avoid cron jobs. You can maybe then use that as a seed for your random. That way everyone will get the same random result that week. – ThePerson Jun 27 '14 at 21:06

1 Answers1

0

You will want to do some thing like this:

<?php
$random_key = rand(0, count($product_array) - 1);
$href = $product_array[$random_key];
echo '<a href="'.$href.'"'>Product Link</a>;
?>

The above gets a random array index between 0 and the max possible index for the array and then you can use this random index to specify the index that you want from the array.

If you need the product of the week to not be random every time you could store the value from the above could in a database and every time you run the cron you delete the old value and put in the new product of the week.

  • Thanks for this drinky, but when trying this I get the error message "Unsupported operand types" on the ` $random_key = rand(0, $product_array - 1); ` Tried troubleshooting but no luck, any suggestions? – FynnaT Jun 29 '14 at 09:51
  • My bad, forgot to put the count in, try it now – Scott Drinkwater Jun 30 '14 at 11:09
  • Wahoo thank you Drinky! But just one more question, will this run once a week or will I need to use a cron job? – FynnaT Jul 01 '14 at 11:36
  • All this code above does is select a random product from your array and put it in a link. You would then need to store this random product in a database. You can cron this script and store the product then have some separate code which will then pull the current product of the week from this database. – Scott Drinkwater Jul 01 '14 at 14:44