Get data from url

<?php
   echo "Hello, " .$_GET['name']; ?> //get the name from url. for example: ?name=david

   echo "hello, $name"; //$name can use directly if we use double quote.

?>

Php inside an html

<?= "Hello, " . $_GET['name']; ?> //shortcut for <?php echo "hello"; ?>
  • security issue that users can send malicious parameters.

This function resolved the security issue

echo "Hello, " . htmlspecialchars($_GET['name']); //allow only basic text characters to send by users

Arrays

$emptyarray = []; //create an empty array
    $names = [
            'Jeff', 'John', 'Mary'
        ];
    foreach ($names as $name){

        echo "<li>$name</li>"; //display as list array
    }

Add or remove items from an Array

//add new item in key value pair
$person['name'] = 'myname'; 

//add new item to an array
$cars = ['ford', 'fiat'];
$cars[] = 'bmw';

//remove item
unset($cars['ford']);


Keys value pair Array

$person = [
        'Age' => 31,
        'Hair' => 'Brown'
    ];

   foreach ($person as $key => $value) {
        echo "<li><b>$key</b>: $value</li>";
}

//remove item
unset($person['age']);

Booleans with if / else

// ? -true
// : - false
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody'); //harsh!

//normal if/else
if ($a=2) 
   echo "Company blocked";
else {
   echo "Company NOT blocked";
}
Categories: PHP