phparray-maparray-walkarray-reduce

Display array result in html table using array_walk or array_map


I am working with users data inside array and I want to print user data inside html table without using foreach loop but alternative of that using array_walk()

<?php 
 $users=$this->db->get('user')->result();
 echo '<table><tr><th>Name</th><th>Edit</th></tr><tbody>';
 function myfunction($value,$key)
{
     echo '<tr><td>'.$value.'</td><td>Edit</td></tr>';

}
echo '</tbody></table>';
$a=array("a"=>"user1","b"=>"user2","c"=>"user3");
array_walk($a,"myfunction");

?>

Expected output:

Name     Edit

user1   edit

user2   edit

user3   edit

Solution

  • You are confusing where you put the PHP code.
    Try with this:

    <?php
    function myfunction($value, $key) {
         echo '<tr><td>'.$value.'</td><td>Edit</td></tr>';
    }
    
    $a = array("a" => "user1", "b" => "user2", "c" => "user3");
    
    $users = $this->db->get('user')->result();
    echo '<table><tr><th>Name</th><th>Edit</th></tr><tbody>';
    array_walk($a, "myfunction");
    echo '</tbody></table>';
    ?>