syrkull
syrkull

Reputation: 2344

define multiple results all at the same time in php

I have $config variable that have arrays inside it. In smarty I assign the variable like this:

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

when I call it, I used this : {$config.wateverarrayyouwant} now I want to do the same thing with php. I want to define them in the same manner. How can I define all the arrays in $config in just one line? I only know how to define a variable one at a time by using this :

define('wateverarrayyouwant', $config['wateverarrayyouwant']);

I tried changing wateverarrayyouwant to a variable because it can be any array :

define('$wateverarrayyouwant', $config[$wateverarrayyouwant]);

but the code above does not work. what is a good way to achieve what I want?

Upvotes: 1

Views: 118

Answers (3)

syrkull
syrkull

Reputation: 2344

This question cannot be done. because I am trying to define a variable as a constant. I was just thinking about how can I reduce the letters for variables and never though that I better leave them alone. Logically, why do somebody need to change $config[$wateverarrayyouwant] to wateverarrayyouwant. I was only thinking about maintaining a neat code. but now I am thinking about it.. it is better to leave it as it is : $config[$wateverarrayyouwant]

This can be done with:

foreach($config as $key => $value){
    $$key = $value;
}

Upvotes: 1

Jon
Jon

Reputation: 4736

If you want to create a define for each key value pair in the array you can use:

<?php
foreach($config as $key => $value) {
    define($key, $value);
}

I will note however that you cannot define array values, all define's must be scalar:

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values.

If you check the OP's answer for further explanation of what he's trying to achieve, it can be done with:

<?php
foreach($config as $key => $value){
    $$key = $value;
}
?>

Upvotes: 2

prodigitalson
prodigitalson

Reputation: 60413

You may not even want to use define here. define is used to create constants not plain variables and that carries with it certain connotations:

  • they are immutable for the life of the script
  • they must be scalar

If you just want an array variable then define it like normal with:

$whatever = array(
  'key1' => 'value1'
);

Upvotes: 0

Related Questions