I’m building my first snippet but I’m blocked with a PHP problem.
I have several classical variables (2 for each weekday) :
$place_monday_midday = "11";
$place_monday_evening = "11";
$place_tuesday_midday = "12";
$place_tuesday_evening = "15";
$place_wednesday_midday = "19";
$place_wednesday_evening = "11";
But I also have several “if” to check the current week day ($current_day) and if we are the midday or the evening ($when)
After all this tests on dates and times, I get this :
$where = '$place_'.$current_day."_".$when;
If I do
echo $where; I get
$place_monday_evening which is correct.
My question is : how to get the value (11 in this example) as return for my snippet ?
With snippets, you can just output with PRINT, or better yet you can call a chunk and output into the chunk variables. I assume you will want to output all those variables, that can be done manually or programmatically
Give this a try. I think by having the
' at the start of
$place you’re initialising a string rather.
$where = $place_'.$current_day.'_'.$when;
@lkfranklin That’s invalid syntax.
When you have the name of a variable in a variable (in your example,
$where = '$place_monday_evening';), you can use
$$variable to get its value, like
Off-hand I’m not entirely sure if that expects the value of
$where to start with
$or not, so you can try with or without the
$place to see which one works.
That said, this is an awfully old, and difficult to understand mechanic, which I honestly wouldn’t recommend using.
Instead, consider a different pattern, like an array lookup:
$map = [
'monday' => [
'midday' => 11,
'evening' => 11,
'tuesday' => [
'midday' => 12,
'evening' => 15,
Still not the best code (try checking if keys/values exist before accessing them) but less magical and much easier to understand.
In MODX snippets, the output must always be in a
return. Other methods, like
var_dump are useful for simple debugging, but bypass the MODX parser and can lead to unexpected results.
The best PHP resource, besides the official docs, is probably PHP: The Right Way which goes into way more than you’ll need, but may be a good reference to keep in mind.
OK I got it !
Thanks for the array lookup