views:

254

answers:

2

I have a template system, that replaces text such as {HEADER} with the appropriate content. I use an array like this, that replaces the key with the value using str_replace.

$array = array("HEADER","This is the header");
    foreach($array as $var => $content) {
       $template = str_replace("{" . strtoupper($var). "}", $content,$template);
    }

Now im trying to use a defined variable like this:

define("NAME","Site Name");

Inside the value for the header. So I want the defined variable to be inside the array which gets replaced so it would look like this, but it doesn't work.

$array = array("HEADER","Welcome to ".NAME."'s website!");

Any ideas? tell me if im not clear

+1  A: 

Shouldn't your array line be:

$array = array("HEADER" => "Welcome to ".NAME."'s website!");

Since you are accessing the array items by key and value?

salathe
A: 

The way you are looping through the array, using :

foreach($array as $var => $content) {
    // ...
}

makes me think you should use an associative array for your $array.

i.e., it should be declared this way :

$array = array("HEADER" => "Welcome to ".NAME."'s website!");


And, as a demonstration, here's an example of code :

$template = <<<TPL
Hello, World !
{HEADER}
And here's the content ;-)
TPL;

define("NAME","Site Name");

$array = array("HEADER" => "Welcome to ".NAME."'s website!");
foreach($array as $var => $content) {
   $template = str_replace("{" . strtoupper($var). "}", $content,$template);
}

var_dump($template);

And the output I get it :

string 'Hello, World !
Welcome to Site Name's website!
And here's the content ;-)' (length=73)

Which indicates it's working ;-)
(It wasn't, when $array was declared the way you set it)


When using this :

$array = array("HEADER","This is the header");
var_dump($array);

You are declaring an array that contains two items :

array
  0 => string 'HEADER' (length=6)
  1 => string 'This is the header' (length=18)


On the other hand, when using this :

$array = array("HEADER" => "This is the header");
var_dump($array);

You are declaring an array that :

  • contains only one item
  • "HEADER" being the key
  • and "This is the header" being the value

Which gives :

array
  'HEADER' => string 'This is the header' (length=18)


When using foreach ($array as $key => $value), you need the second one ;-)


And, purely for reference, you can take a look at, in the manual, the following pages :

Pascal MARTIN
my bad i am using that sort of array, i just typed it on the fly here. yes i know how to use arrays and foreach..
john
does this mean your problem is solved ? Or is there still something that *doesn't work* ? If so, can you edit your question to add some informations to say more about what *doesn't work* mean ?
Pascal MARTIN