Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I subscript an array variable inside a double quoted PHP string?

Tags:

php

I have an array of custom hooks I'd like to schedule, built along these lines:

public function __construct(WPSM_Logger $injected_logger = null) {
    $this->cron_hooks[WPSM_CRONHOOK_SENDQUEUE] = array ("frequency" => 60);
}

Then, in the constructur for my Scheduler class, I would like to loop through $this->cronhooks and schedule each hook in that array. I normally prefer straight and simple variable expansion within double quoted strings, like what I do with $name below, but I can't seem to figure out how to do this with an array and subscript.

foreach ($this->cron_hooks as $name => $options) {
    $freq = $options["frequency"];
    echo "Hook '$name' will run every $freq seconds.";  
}

I would like to do away with the intermediary $freq = $options["frequency"]; line, and have something like this in the echo line:

foreach ($this->cron_hooks as $name => $options) {
    $freq = $options["frequency"];
    echo "Hook '$name' will run every $options['frequency]seconds.";    
}

However, I simply can't get that to work. Is there something special I'm missing, or do I really have to drag an extra variable along to my party?

like image 717
ProfK Avatar asked Jan 15 '12 11:01

ProfK


1 Answers

have you tried this?

foreach ($this->cron_hooks as $name => $options) {
    echo "Hook '$name' will run every ${$options['frequency']} seconds.";    
}
like image 58
Alex Avatar answered Oct 09 '22 15:10

Alex