April 4, 2012

How do I name these PHP arrays?

Question by absentx

Lets say I need three arrays, ford, chevy and dodge. Each array has three items:

$ford['engine'] = 'something';
$ford['color'] = 'something';
$ford['price'] = 'something';

$chevy['engine'] = 'something';
$chevy['color'] = 'something';
$chevy['price'] = 'something';

$dodge['engine'] = 'something';
$dodge['color'] = 'something';
$dodge['price'] = 'something';

I can write that out no problem and it doesn’t take too long. But, lets say I need fifty or sixty arrays that I need to make, all with ten to twenty different items. I want to put a variable at the top of each array’s file to denote what the array name will be, but I am not quite clear on the syntax and I am not too familiar with $$ or how I would use that with arrays:

$name = 'ford';

$(I want this to be "$name")['engine'] = 'something';
$(I want this to be "$name")['color'] = 'something';
$(I want this to be "$name")['price'] = 'something';

I have also considered just doing this:

$name = 'ford';

$view[$name.'_engine'] 
$view[$name.'_color'] 
$view[$name.'_price'] 

Can I get some suggestions on the best way to approach this?

Answer by Starx

Write a small function to do that

$cars = array(); //Create an array to hold the values    
function writeArray($car, $var1, $var2, $var3) {
     global $cars;
     $cars[$car] = array('engine' =>  $var1, 'color' => $var2, 'price' => $var2);
}
//Now use it like
writeArray('Chevy', $something, $something, $something);

//If you want to access the array in the form of $ford['engine'] then use this

extract($cars); //This will split the array into small array accessible by model 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!