phpfunctionnowdoc

PHP us a string variable as an argument for function


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.


Solution

  • 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);
    }