-1

It's probably not possible, and I'm damn fool. But, I am trying to build an array in PHP, where some of the elements are variables.

$myArr = array();
$i = 1;
$n = 5;
for($i = 1; $i <= $n; $i++) {
  if($i === 1){
      $myArr["k$i"] = array(
          'description' => 'Some special text for the k1 element',
          'type' => 'some type',
          'foo' => 'bar',
      )
  }else{
      $myArr["k$i"] = array(
          'description' => 'This is the number ' . $i . ' element description.'
          'type' => 'some type',
          'foo' => 'bar',
      )
  }
}
return $myArr;

The results should be:

$myArr = [
  k1 => [
    'description' => 'Some special text for the k1 element',
    'type' => 'some type',
    'foo' => 'bar',
  ],
  k2 => [
    'description' => 'This is the number 2 element description.'
  ...
  ],
] // ending bracket for the $myArr array

PHP complains most often about the curly-bracket closing the IF statement. Any suggestions would be greatly appreciated.


EDIT

The suggestion to look at some long list of 'Common Syntax Errors' is not the answer, and not specific enough of an answer to help me in a timely manner. Also, I simply did not FIND that solution while searching for answers to my question -- perhaps the 'Common Syntax Errors' solution is not properly tagged?

Also, I posted THIS question because the many other questions I managed to find and review, related to PHP arrays, never showed me how to handle variables WITHIN the array. I posted MY question, with example code, in the hopes that a future coder might find how to handle variables WITHIN the array syntax.

  • 1
    You're missing semicolons after your two assignment statements before the closing curly brackets. – Kevin Y Jun 09 '22 at 23:58
  • Does this answer your question? [PHP parse/syntax errors; and how to solve them](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) – CBroe Jun 10 '22 at 07:16
  • @KevinY -- Thank you. That was very helpful, and I do believe it was why PHP was getting hung up on the curly-brace for the IF statement. I would vote this comment up, but I don't see the option -- perhaps I do not have enough reputation on SO. Anyway, thank again. – Robert West Jun 10 '22 at 11:27

1 Answers1

-1

Your code is correct but you forgot semicolons and commas

$myArr = array();
$i = 1;
$n = 5;
for($i = 1; $i <= $n; $i++) {
  if($i === 1){
      $myArr["k$i"] = array(
          'description' => 'Some special text for the k1 element',
          'type' => 'some type',
          'foo' => 'bar',
      );
  }else{
      $myArr["k$i"] = array(
          'description' => 'This is the number ' . $i . ' element description.',
          'type' => 'some type',
          'foo' => 'bar',
      );
  }
}
return $myArr;
vivek ghetia
  • 102
  • 6
  • I did find the missing comma within the array as well, thank you Vivek. @KevinY 's comment above was the most helpful response. – Robert West Jun 10 '22 at 12:13