Question

I have this following code.

$sn_count = 1;
  foreach($points as $point){
    echo "<div class=\"points\">";
    echo "<div class=\"serial\">".$sn_count."</div>";
    echo "<div class=\"pointsdesc\">";
    echo $point['points_description'];
    echo "</div></div>";
    $sn_count++;
  }

Is it possible to assign the above code to a variable $pointsvar

Everytime i use $pointsvar the above code should be printed. Please help. Thanks

Was it helpful?

Solution

Functions is your solution.

function printPointVars($points)
{
    $sn_count = 1;
    $html = '';
    foreach($points as $point){
        $html .= "<div class=\"points\">"
            . "<div class=\"serial\">".$sn_count."</div>"
            . "<div class=\"pointsdesc\">"
            . $point['points_description']
            . "</div></div>";
        $sn_count++;
    }
    echo $html;
}

printPointVars($points);

OTHER TIPS

Use a function... not a variable

function pointvar() {
    //Your code here    
}

If you want get or set your variable

function pointvar($var = null) {
    if(!empty($var)) {
        $pointvar = $var;
    }
    //Your code here
    return $pointvar;
}

pointvar(12); //Set pointvar and execute your code
$newVar = pointvar(); //Get pointvar value and execute your code

use .= to assign something to the end of a variable... Something like this:

$sn_count = 1;

$pointsvar = "";

foreach($points as $point){
  $pointsvar .= "<div class=\"points\">";
  $pointsvar .="<div class=\"serial\">".$sn_count."</div>";
  $pointsvar .="<div class=\"pointsdesc\">";
  $pointsvar .=$point['points_description'];
  $pointsvar .="</div></div>";
  $sn_count++;
}

echo $pointsvar;

If you want to call something like this alot, just move this into a function , and pass in the $points array.

Is it ok if $pointsvar is static? (set once, then always at that value?) Is so, just change your echoes to become assignents...

$pointsvar = '';
$sn_count = 1; 
  foreach($points as $point){ 
    pointsvar = pointsvar."<div class=\"points\">"; 
    pointsvar = pointsvar."<div class=\"serial\">".$sn_count."</div>"; 
    pointsvar = pointsvar."<div class=\"pointsdesc\">"; 
    pointsvar = pointsvar.$point['points_description']; 
    pointsvar = pointsvar."</div></div>"; 
    $sn_count++; 
  } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top