1

i have this code

for($i=0; $i<2; $i++){  
   $array = array(
       'NAME' => 'name'.$i,
       'NUMBER' => 'peserta'.$i,
   );
}

i wanna get output like this

[
 "NAME" => name1,     
 "NUMBER" => number1,
],
[
 "NAME" => name2,     
 "NUMBER" => number2,
]

what should I return / do ?

2
  • $array['data'][] = array( ... ? Commented Apr 21, 2020 at 17:51
  • like that i have edit the post. i hope you get my point Commented Apr 21, 2020 at 17:55

3 Answers 3

2

you can not display multiple arrays in one key but you can add them to one array , like this.

you should instead of:

$array = ...

use:

$array[] = ...
Sign up to request clarification or add additional context in comments.

Comments

1

change your code to this:

for($i=1; $i<3; $i++){
   $filepath = public_path('template.rtf');    
   $array[] = array(
       'NAME' => 'name'.$i,
       'NUMBER' => 'peserta'.$i,
   );
}

print_r($array); // or var_dump($array)

8 Comments

@MuhammadZainulMutaqin yes, return $array
i've tried but output was empty, am I wrong ? check 3v4l.org/dDGiL
@MuhammadZainulMutaqin oh, got it, I edited my answer. you must use print_r or var_dump to see your array
This would actually output name0 and peserta0 in the first iteration.
yes @bestprogrammerintheworld. so how to output both of the iteration?
|
1

If you just want to output each item and echo an array each time you could do this:

<?php
foreach(range(1,2) as $i) {  
    $array = array(
        'NAME' => 'name'.$i,
        'NUMBER' => 'peserta'.$i,
    );
    echo '<pre>';
    print_r($array);
    echo '</pre>';
 }

If you want to create an array:

foreach(range(1,2) as $i) {  
    $array[] = array(
        'NAME' => 'name'.$i,
        'NUMBER' => 'peserta'.$i,
    );
}
echo '<pre>';
print_r($array);
echo '</pre>';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.