Wednesday, March 12, 2014

Most Useful PHP Snippets

Dumping arrays or objects with HTML markup text as member. This prevents creating iFrame and similar tags in your debug output.


<?php
$var = array(
'<iframe src="new_file.html">',
'<iframe src="new_file.html">'
);

if (is_array($var) || is_object($var)) {
  $c = print_r($var,TRUE); 
  echo "<pre style='background:yellow;padding:10px;'>";
  echo htmlentities($c, ENT_QUOTES); 
  echo "</pre>";
} else {
  echo "<pre style='background:yellow;padding:10px;'>";
  var_dump(htmlentities($var));
  echo "</pre>";  
}
?>

Timing

<?php
$start = microtime(true);
sleep(1);
$end = microtime(true);
echo "<hr> script executed for " 
. substr(($end - $start), 0, 6) 
. " seconds";
?>

if, elseif and else among HTML markup

<?php $b =  'news/index'; ?>     
   
<?php if ($b == 'news/create') { ?>   
    <li> <a href="/news/index">Home</a> </li>
    <li> <a class="active" href="#">Add News</a></li>                 
<?php } elseif (substr($b, 0, 10) == 'news/index') { ?> 
    <li class="active"><a href="/news/index">Home</a></li>
    <li><a href="/news/create">Add News</a></li>                  
<?php } else {  ?>
    <li><a href="/news/index">Home</a></li>
    <li><a href="/news/create">Add News</a></li>              
<?php } ?>

Convert object to array
function object_2_array($result)
{
    $array = array();
    foreach ($result as $key=>$value)
    {
        if (is_object($value))
        {
            $array[$key]=object_2_array($value);
        }
        elseif (is_array($value))
        {
            $array[$key]=object_2_array($value);
        }
        else
        {
            $array[$key]=$value;
        }
    }
    return $array;
}

Table generator with if and foreach loop

<table class="table table-striped">
  <thead>
   <tr>
    <th>Email</th>
    <th>Edit</th>
    <th>Delete</th>
   </tr>
  </thead>
  <tbody>
<?php if(count($users)): foreach($users as $user): ?> 
  <tr>
   <td><?php echo ; ?></td>
   <td><?php echo ; ?></td>
   <td><?php echo ; ?></td>
  </tr>
<?php endforeach; ?>
<?php else: ?>
  <tr>
   <td colspan="3">Found no users.</td>
  </tr>
<?php endif; ?> 
  </tbody>
</table>

I found nice gist by Joost van Veen - https://gist.github.com/accent-interactive/3838495

No comments:

Post a Comment