php - Variable name set to key and its value set to value in an array


I want to set up a load of variables then loop though them adding them to an array with the key set as the variable name, something like below.

I am just not sure how you create the loop.

// create an array
$array = array();

// Set up Variable
$green  = "31d944";
$red    = "d92929";
$blue   = "1b43d9";
$pink   = "d96ad8";
$orange = "d98225";

// Loop though - not sure how this would work...
for($i=0; $i<5; $i++){
    $array[] = $varNmae => $green;

// Output something like below
$array['green']; // output '31d944'
$array['red'];  // output 'd92929'
$array['blue']; // output '1b43d9'
$array['pink']; // output 'd96ad8'
$array['orange']; // output 'd98225'



What is the thinking in defining the variables and then adding them to an array, instead of just initialising the array?

// Can't you just use this?
$ary = array(
  'green' => '31d944',
  'orange' => 'd98225',

Could be looped with

foreach ($ary as $color => $val) {
  echo "{$color} is equal to {$val}";

Or accessed as

echo $ary['green'];

People are also looking for solutions to the problem: php - API with external generated session ID


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.