PHP tips and shortcuts

If and else statement with isset

Usual method

<?php
if(isset($_SERVER['HTTP_REFERER'])){
    // Print HTTP_REFERER
    echo $_SERVER['HTTP_REFERER'];
}else{
    // Print nothing
    echo ""; 
}
?>

Shortcut

<?php
     echo isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
?>

Same in Laravel

{{ $_SERVER['HTTP_REFERER'] or 'empty' }}

 

Loop

<?php foreach ($people as $p) : ?>
 <li><?= $p; ?></li>
<?php endforeach; ?>

Loop (Laravel blade syntax)

@foreach ($people as $p)
 <li> {{ $p }} </li>
@endforeach

Loop with if and else (Laravel)

@forelse ($people as $p)
  <li> {{ $p }}</li>
@empty
  <li> Empty </li>
@endforelse

 

Same loop

@foreach($errors->all(':message') as $msg)

@foreach($errors->all() as $msg)

 

 

Get class methods

foreach(get_class_methods($google) as $key => $value){
     echo $value . "<br/>";
}

instanceof

echo ($dog2 instanceof Dog)? "True" : "False";

 

get_class_methods

foreach(get_class_methods($dog1) as $key => $value){
     echo $value . "<br/>";
}

 

unless

@unless(empty($var))
 {{$var}}
@endunless

They are the same

@if(!empty($var))
 {{$var}}
@endif

 

Remove multiple keys from associative array

$removeVesselKeys = array('key_to_remove', '1011', '1015', '1016', '3002', '3003', '2009', '2002');

foreach ($removeVesselKeys as $key){ 
 unset($shipdata[$key]);}

print_r($shipdata);
echo count($shipdata);

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top