0

I am trying to create an associative array using php. My desired output is

Array
(
     [key] => fl_0_sq
),
Array
(
     [key] => fl_1_sq
)

The code is

  $max_val = 2;  
  for($i=0; $i<$max_val; $i++)
  {
        $flr_arr .= "array('key' => 'fl_".$i."_sq'),";      
  }
  print_r($flr_arr);

Output is

array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),

Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.

3 Answers 3

1

You could do this:

<?php

$flr_arr = [];

$max_val = 2;
for ($i = 0; $i < $max_val; $i++) {
  $flr_arr[][key] = 'fl_' . $i . '_sq';
}

$output = "<pre>";

foreach ($flr_arr as $i => $flr_arr_item) {
  $output .= print_r($flr_arr_item, true);
  if($i < count($flr_arr)-1){
    $output = substr($output, 0, -1) . ",\n";
  }
}
$output .= "</pre>";

echo $output;

The output:

Array
(
    [key] => fl_0_sq
),
Array
(
    [key] => fl_1_sq
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks mate. Tomasz solution is pretty close. I need to insert a comma though after each array ends.
@PrithvirajMitra Here you go ;) now it has the exact formatting you want
Sorry for replying late. Yes that works really great. I had some other key elements so I have to adjust anyway. Thanks once again for your help.
0

I'm not exactly sure what you want to do, but your output could be done by this:

  $max_val = 2;
  for($i=0; $i<$max_val; $i++)
  {
        $flr_arr = [];
        $flr_arr['key'] = 'fl_".$i."_sq';
        print_r($flr_arr);
  }

2 Comments

Almost there. Thanks a lot. Last thing I need to know that is how can I insert a comma after each array ends.
echo ',' isn't enough?
0

You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:

$flr_arr[] = array("key"=>"fl_$i_sq");

Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -

array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.