-3

I am trying to set a variable as a string and then use that variable in a while loop function.

<?php
$assoc = <<<'EOF'
$users[]=array('name'=> $row['name'], 'foreman_position'=> $row['foreman_position'], 'status'=> $row['status'], 'emp_num'=>$row['employee_num'],'sen_num'=> $row['seniority_num']);
EOF; 


  while($row = mysqli_fetch_assoc($result)) {
      echo $assoc;

   }

When evaluated I would like it to look like this:

while($row = mysqli_fetch_assoc($result)) {   
     $users[]=array('name'=> $row['name'], 'foreman_position'=> 
     $row['foreman_position'], 'status'=> $row['status'], 'emp_num'=>   
     $row['employee_num'],'sen_num'=> $row['seniority_num']);
   }

If I put the syntax in by hand it works fine but the variable is expressing as the string. Any help is greatly appreciated.

deceze
  • 510,633
  • 85
  • 743
  • 889
John
  • 3
  • 1
  • 1
    *Technically*, you could probably do this using `eval()`. But this is an exceptionally bad practice, you should never have a string of code that you want to execute. This type of code is very difficult to maintain and debug. – rickdenhaan Dec 23 '18 at 22:09
  • Thanks I really appreciate it! – John Dec 23 '18 at 22:23

1 Answers1

0

That is just not how this works. If you want to make a piece of code reusable or just move it elsewhere, you use functions:

function extractResult(array $row, array &$output) {
    $output[] = [... => $row[...], ...];
}

$users = [];

while ($row = mysqli_fetch_assoc($result)) {
    extractResults($row, $users);
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks for your reply. I am trying to use functions to consolidate my code. I have a few different queries to my db that I use the same type of while statement for but have different elements in them. I am trying to make them generic and pass the specific info via a string. So if I understand you correctly, I should make a separate function for each time I want to fetch and array? – John Dec 23 '18 at 22:20
  • Yes, the loop is pretty minimal overhead and not really something you should try to eliminate. If you really wanted to you could look into something like https://stackoverflow.com/a/53778075/476, or look into classes and subclassing a specific extraction method. – deceze Dec 24 '18 at 06:01