mac389
mac389

Reputation: 3133

Scope of variables in PHP file passed to Smarty

I would like to know why the array isn't updated with a string concatenation in the following example.

$scripts = array( "jquery.js","bootstrap.min.js",
               "jquery-jvectormap-1.0.min.js",
               "jquery-jvectormap-us-aea-en.js",
               "protoFluid.js");

foreach($scripts as $script)
$script = "/scripts/".$script;                 

$smarty -> assign('scripts',$scripts);

I expected this code to, for example, change $scripts[0] from jquery.js into /scripts/jquery.js. However, the Smarty debug console shows the following.

Smarty_Variable Object (3)
->value = Array (5)
0 => "jquery.js"
1 => "bootstrap.min.js"
2 => "jquery-jvectormap-1.0.min.js"
3 => "jquery-jvectormap-us-aea-en.js"
4 => "protoFluid.js"
->nocache = false
->scope = "Smarty root"

Upvotes: 1

Views: 245

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

Depending on whether you still need the original array afterwards, you could use array_map() to create a modified copy:

$smarty->assign('scripts', array_map(function($script) {
    return "/scripts/$script";
}, $scripts));

Upvotes: 1

Zdenek Machek
Zdenek Machek

Reputation: 1744

Foreach is working on a copy of the array, you have to do:

foreach($scripts as &$script)
    $script = "/scripts/".$script; 

Upvotes: 2

Related Questions