In: Computer Science
Can you provide with examples of these PHP common functions - echo, print, filter_input, isset, empty, is_numeric, include, include_once, header, htmlspecialchars, nl2br, strops(), explode(), implode(), count()
echo(), print()
<!DOCTYPE html>
<html>
<body>
<?php
echo "echo example";
echo "Hello world!<br>";
print "print Example<br>";
print "Hello world!<br>";
?>
</body>
</html>
Output:
echo example
Hello world!
print example
Hello world!
filter_input()
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) ===
false) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
INPUT_GET - Filter Type
"email" - Variable name to be filtered.
FILTER_VALIDATE_EMAIL - Filter type
RETURNS - false on failure and value of the variable on success, NULL if the variable is not set.
isset() , empty()
<?php
$var1 = 0;
// True because $var1 is set
if (isset($var1)) {
echo "Variable 'var1' is set.<br>";
}
// True because $var1 is empty
if (empty($var1 )) {
echo "Variable 'var1 ' is empty.<br>";
}
$var2 = null;
// False because $var2 is NULL
if (isset($var2)) {
echo "Variable 'var2' is set.";
}
?>
is_numeric()
<?php
$a = 32;
echo "a is " . is_numeric($a) . "<br>";
// RETURNS TRUE if variable is a number or a numeric string, FALSE otherwise
// Output : a is 1
?>
include , include_once
include 'filename';
Including of one php file into another we use include
include_once 'filename';
Including of one php file into another we use include_once but if the file is already included it will not include again.
header()
The header() function sends a raw HTTP header to a client.
<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
htmlspecialchars()
Convert the predefined characters "<" (less than) and ">" (greater than) to HTML entities:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
// output : This is some <b>bold</b> text.
nl2br()
Insert line breaks where newlines (\n) occur in the string:
<?php
echo nl2br("One line.\nAnother line.");
?>
Output
One line.
Another line.
strops()
Find the position of the first occurrence of "php" inside the string:
<?php
echo strpos("I love php, I love php too!","php");
?>
Output : 7
explode()
Break a string into an array:
<?php
$str = ""Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
implode()
Join array elements with a string:
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
Output : Hello World! Beautiful Day!
count()
Return the number of elements in an array:
<?php
$cars=array("car1","car2","car3");
echo count($cars);
?>
Output: 3