简体   繁体   中英

PHP - generic variable variable name of a variable

I am quite new on php and I got stuck with a problem.. I have an array with the day of the week call

$days = array( 'monday', 'tuesday', 'wednesday', 'thurday', 'frieday', 'sunday',  'saturday' );

also got a for loop index i=0 i<7 i++ that go along all day of the week so I dont need to repeat the code 7 times (1 for each day) and I got open, close, hours and lots of info about each day..

so i some part I loop I need to asing a value to a generic variable called: $ini_XXXXX_close where XXX is the day of the week so it's ($ini_$dias[$i]_close) generally speaking

when I tried to do: $ini_$dias[$i]_close=0; I got error... So what I did is use a third variable..

$indexcloseini="ini_$dias[$i]_close";

and then $$indexcloseini=0 which sucessfull generate the variable $ini_XXXXX_close=0; ( doble $$ read it from php manual)

But the problem is when I tried later to compare that variable with any other value inside and IF sentence.. The only way to acomplish is already to use an intermediate variable..

Is there any other easy way to do this.. I read php reference manual and tried using {!} and lots of thing but cant get it work..

Is there any function to transform this " $ini_$dias[$i]_close " to string so I could then make

$*STRING CONVERSION FUNCTION of $ini_$dias[$i]_close* 

to create the variable composed by many variable values ?

Personally I would not go that route. It is complex, confusing and hardly ever a usefull solution. HJave you considered using a nested array for storing the values? Or even creating an object?

As an array, you could have:

$ini = array('monday'=>array(), 'tuesday'=>array(), //etc);
$ini[$day]['closeStatus'] = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM