'echo variable from a string
I had created this function that simply accepts some arguments to take some information from a table, and echoes the result mixed with some HTML that is passed with args
functions.php
function loop_show($conn,$table,$div){
$string_query="select * from $table";
$sql=mysqli_query($conn,$string_query);
while($result=mysqli_fetch_array($sql)){
echo "$div";
}
}
when calling the function from another page
index.php
<?php loop_show($conn,"projects","<div>Hello $result[name] , Your age is $result[age]</div>") ?>
the problem is that I don't have $result variable in index.php but I just want to tell the function that it should echo the $result in specified place
Solution 1:[1]
You can use a callback function for this.
function loop_show($conn,$table,$divfun){
$string_query="select * from $table";
$sql=mysqli_query($conn,$string_query);
while($result=mysqli_fetch_array($sql)){
echo $divfun($result);
}
}
loop_show($conn,"projects",
function($result) {
return "<div>Hello $result[name] , Your age is $result[age]</div>";
} );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
