Geeting error Undefined variable: desc even already defined as empty

123 Views Asked by At

I want to print all user names one by one which is array format, so instead of using foreach loop I am using array_walk() and it is printing all user data one by one but as per requirement data should be print in html table so defined one varaible $desc as empty and concatenate html code(table body table heading with users name) and at the end echo $desc but getting error:

expected output:


<html> 
<body> 

<h2>Basic HTML Table</h2> 

<table > 
<tr> 
<th>username</th> 

</tr> 
<tr> 
<td>user1</td> 

</tr> 
<tr> 
<td>user2</td> 

</tr> 
<tr><td>user3</td></tr> 
<tr><td>user4</td></tr> 


 <?php 
$users=$this->db->get('users')->result();
$desc = '';
 $desc .= '<table class="table table-hover" id="catgeory_list">
                      <thead>
                        <tr>
             <th>User Name</th>   
        </tr>
                      </thead>
                      <tbody>';
function myfunction($value)
{
  echo $desc .= '<tr><td>'.$value->name.'</td></tr>';
}
$a = (array) $users;
array_walk($a,"myfunction");
$desc .= '</tbody></table>';
?>

If I use without table it is working here is the code which I have use without table

 <?php 
    $users=$this->db->get('users')->result();
    function myfunction($value,$key)
    {
      echo $value->name;
    }
    $a = (array) $users;
    array_walk($a,"myfunction");
    ?>

Output should print user name in html table assigned in $desc varaible using concatenation

1

There are 1 best solutions below

2
Nathan Dawson On

Your function has no access to the $desc variable. There is a way to resolve that but even then, it doesn't make sense to do echo $desc .= ....

You're using array_walk but I think this could be a good use case for map instead. You want to map over the array and convert each element to an HTML string. That can then be mixed with implode to return all of the elements as a string.

Example:

$users = $this->db->get('users')->result();

$users_table = array_map(function ($user) {
    return '<tr><td>' . $user->name . '</td></tr>';
}, $users);

echo '<table> ... '; // open table here.
echo implode('', $users_table);
echo '</table>'; // and finally, close it.

Why map? You'll often split up the process of generation and output. This gives you the option to do that. If you wanted to get your original code working there is a simple solution. Forget $desc altogether and stick to echo. Echo the table opening, then walk the array, and finally the table closing.