Weekly shuffle of array - php

I have a set of 4 HTML list items and I'd like to shuffle the order they appear in once a week. I was wondering if anyone out there had a nice, elegant solution to this?
As always, I'd be enormously grateful for any input you might have!
UPDATE:
Unfortunately, even with the necessary .htaccess overrides, I just can't get any srand() based solutions to work on this particular server sadly, but have the following which could be used instead - at the moment, it only returns one list item - how could I modify it to show the four required? Once again, any ideas would be gratefully received :)
function RandomList($TimeBase, $QuotesArray){
$TimeBase = intval($TimeBase);
$ItemCount = count($QuotesArray);
$RandomIndexPos = ($TimeBase % $ItemCount);
return $QuotesArray[$RandomIndexPos];
}
$WeekOfTheYear = date('W');
$RandomItems = array(
"<li>North</li>","<li>South</li>","<li>West</li>","<li>East</li>");
print RandomList($WeekOfTheYear, $RandomItems);

Here is a simple and - I guess - pretty elegant solution, which does not involve storing values in a database, setting up cronjobs and other boring stuff of the like.
Let's pretend you have your list elements in $array:
srand(date('W'));
shuffle($array);
srand();
Now your array is shuffled, and will be shuffled the same way until next Monday.
This has a problem, though: it does not work with the Suhosin patch (installed by default in Debian). Still, now that you know about date('W') it will be easy to come up with an alternate solution yourself.
EDIT: if you don't want to implement your own pseudorandom number generator but you have Suhosin installed, you can put the following line in your .htaccess:
php_value suhosin.srand.ignore 0

Related

Shorter way to add one to an array element OR set array element to 1?

I often create scripts that generate reports that count a lot of different things while looping through mysql query results or lines of a file or something. In doing so, I usually have an array that keeps track of all the different "counts", like this:
$counts[$thingBeingCounted]++;
So at the end I have an array with a bunch of counts that I can then report.
This works great, except PHP blows up on the first "count", since there is nothing to increment yet.
The obvious solution is to make sure it's set first:
if(!isset($counts[$thingBeingCounted])){
$counts[$thingBeingCounted] = 0;
}
$counts[$thingBeingCounted]++;
Or maybe
$counts[$thingBeingCounted] = isset($counts[$thingBeingCounted]) ? $counts[$thingBeingCounted] + 1 : 1;
Either way, the "check if it's set first and then initialize it if needed" really takes away from the simpleness of just slapping ++ on the end of the array element.
I can't just initialize the $counts array with all the potential things to be counted at the start either, as there can potentially be a lot of things it's counting.
Is there any more elegant solution?
$counts["new_el"] = ($counts["new_el"] ?? 0) + 1;
This is the shortest way to properly increment a variable without declaration.
If you really want to make the code more short, you can use error suppression (#$counts["element"]++) but it is not recommended or maybe one of forbidden thing that we should not do
For explanation,
$counts["new_el"] ?? 0
is the same as
isset($counts["new_el"]) ? $counts["new_el"] : 0
so my code above is equivalent to
$counts["new_el"] = (isset($counts["new_el"]) ? $counts["new_el"] : 0) + 1
Sorry for bad English and bad format, i am new in this community and just trying to help another

Wordpress - Passing variable to function - how to correctly pass list of numbers

I am trying to restrict content within a Wordpress template file and am using a plugin called Paid Memberships Pro to do so.
The code below restricts content to members with 'levels' of 1 or 2.
if(pmPro_hasMembershipLevel(array(1,2))){
restricted content goes here
}
The problem comes when I try to use a variable to provide the levels. These levels are held in a custom field group 'restrictions' with field name 'pmpro_id'. I access these levels within the template using...
foreach($restrictions as $restriction){
$temp=get_field('pmpro_id', $restriction->ID );
$temp_array[]=$temp;
}
$levels=implode(',', $temp_array);
If I then pass $levels to pmPro_hasMembershipLevel, this works fine if there is only one level but fails if there are 2 or more. I believe this is because the variable type is then a string rather than integer? I had previously tried to pass the $temp_array directly though I felt this wouldn't work and was correct.
I realise this is probably PHP 101. I have searched but don't really know what I'm looking for to be honest! I am not a developer and this is the last thing holding me back from finishing this project so ANY help anyone could provide would be brilliant. Thanks in advance.
You don't need to implode $temp_array if pmPro_hasMembershipLevel accepts array as its argument. When you implode an array you get string as a return value — that's not what you want here. If you think that the issue might be with the type of values, then you can try to cast them to integers, like this $temp_array[]= (int) $temp;

Accessing variables, named with variables PHP

I am very new to programming and I got a job from school to do a "forecast" weather map from random generated numbers.
I already got 7 different arrays for every day (day1 -> day7) and all the code afterwards to check the required stuff and create the weather map.
Now I have the problem that I'd like to go through all the 7 arrays in 1 for-loop. I asked a friend and I think it's a very tiny thing missing / done wrong...
As I already got all the code afterwards (currently hardcoded for 1 day) I'd be pleased if you could provide me a solution for my (I guess crappy) way, not a totally different way eventhough it's most likely much more efficent what so ever.
I tried it like this:
for($daynr = 1; $daynr < 8; $daynr++){
$dayZ = 'day'.$daynr;
print_r($$dayZ);
...
This works like a charm and gives out array 1-7. But when I try to access a part of dayZ I get stuck:
echo $$dayZ[0][0]
Gives out:
Notice: Undefined variable: in C:\xampp\htdocs\index.php
on line 139
As many stuff later like $temp = explode('/',$$dayZ[$region_nr][3])... need to access the day-array it would be cool to have a solution for that.
Btw, something like echo $day1[0][0] works without problems.
Any help very appreciated, thanks in advance
Best regards
Michael
A cleaner solution would be to place the days in another array. So instead of $day1, $day2 etc you have an array $days containing your arrays for each day.
$days[0][0][0] // monday
$days[1][0][0] // tuesday
// ...
Use
${$dayZ}[0][0]
Keep in mind that this kind of variable format does NOT improve readability or good code.

PHP Change Array Over and Over

I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.

PHP Compare Two Arrays?

I'm trying to compare two entries in a database, so when a user makes a change, I can fetch both database entries and compare them to see what the user changed, so I would have an output similar to:
User changed $fieldName from $originalValue to $newValue
I've looked into this and came across array_diff but it doesn't give me the output format I need.
Before I go ahead and write a function that does this, and returns it as a nice $mtextFormatDifferenceString, can anyone point me in the direction of a solution that already does this?
I don't want to re-invent the wheel..
Since you require "from $originalValue to $newValue", I would go ahead and select the two rows, put them in assoc arrays, then foreach through the keys, saving the ones that aren't equal. Kind of like:
$fields = array_keys($row1);
$changedFields = array();
foreach ($fields as $field) {
if ($row1[$field] != $row2[$field]) {
$changedFields[] = $field;
}
}
I realize you were asking about the existence of pre-built wheels but I felt the solution was pretty simple.
?>
Although you didn't define what format you needed, but well-known diff algorithm is probably for you. Google for PHP diff algorithm and you'll find some suggestions I am sure.
You could get the changed values ($newValue) with array_diff_assoc and then just use the keys ($fieldName) to find the original value $originalValue and output it in anyformat you want

Categories