And let me add one last thing:
In your original code:
$termin_operator = $_POST['termine'] ?? '';
you used the user input as is without any further validation. This is potentially dangerous and should never be done, because the input could be manipulated and instead of your expected comparison operator, you could end up with a piece of malicious code.
With the new code, we now check the values stored in the$termin_operator
variable, so we are safe. Even if the user sends us some weird value, it wouldn’t do any harm, because we control the program flow.
krl
April 5, 2018, 11:06am
22
What a tremendous service, @texnixe !
Both suggestions work fine.
I just wanted to ask about good PHP learning resources and found another thread in this forum:
Hello again,
there are so many websites to learn php and so on but which is really good for newby’s like me?
Thanks again.
krl
May 4, 2018, 3:09pm
23
What would be the easiest way to sort the $posts
ascending if they are >= today and descending if they are < today?
Generally with an if statement, but are you filtering your posts first or what is your setup?
krl
May 4, 2018, 3:16pm
25
Yes, i’m filtering first. I’m using your suggestion from a month ago:
$posts = $data->children()->filter(function($p) use($termin_operator) {
if($termin_operator === '>') {
return $p->date() < time();
} elseif($termin_operator === '>=') {
return $p->date() >= time();
} else {
return $p;
}
});
if($posts->count()):
foreach($posts as $post):
// do something with the post
endforeach;
endif;
Something like this then:
<?php
$termin_operator = 'whatever';// change to your definition
$sortOrder = 'desc';
if($termin_operator !== '<') {
$sortOrder = 'asc';
}
$posts = $data->children()->filter(function($p) use($termin_operator) {
if($termin_operator === '>') {
return $p->date() < time();
} elseif($termin_operator === '>=') {
return $p->date() >= time();
} else {
return $p;
}
});
if($posts->count()):
foreach($posts->sortBy('date', $sortOrder) as $post):
// do something with the post
endforeach;
endif;