$bool = TRUE;
if (is_null($bool))
{
echo 'Variable is NULL';
}
else
{
echo 'Variable is not NULL';
}
// outputs : Variable is not NULL
function display( $number ) {
if( $number <= 10 ){
echo "$number";
display ($number+1 );
}
}
display(0);
// outputs : 012345678910
function print_arr(...$numbers) {
foreach ($numbers as $element) {
echo $element."\n";
}
}
echo print_arr(1, 2, 3, 4);
// outputs : 1 2 3 4
function addition( $x = 10 ){
echo $x + 10;
}
addition(40); // outputs : 50
addition(); // passing no value. outputs : 20
function addition( $x = 10, $y = 20 ){
echo $x + $y;
}
addition(5); // passing one argument. outputs : 25
addition(); // passing no value. outputs : 30
intval()
function.
• To convert string to integer using PHP built-in function, intval(),
provide the string as argument to the function. The function will
return the integer value corresponding to the string content.
$number_str = "10";
$int_number = intval($number_str);
echo gettype($int_number); // outputs: integer
➤ Using explicit Casting.
• To convert string to integer using Type Casting, provide the
literal (int) along with parenthesis before the string literal.
The expression returns integer value of the string.
$str = 10;
$number = (int)$str;
echo gettype($number); // outputs: integer
strval()
function.
• The strval() function is an inbuilt function in PHP and is used to convert
any scalar value (string, integer, or double) to a string. We cannot use
strval() on arrays or on object, if applied then this function
only returns the type name of the value being converted.
$number = 10;
// converts integer into string
$str = strval($number);
echo gettype($str); // outputs: string
➤ Using inline variable parsing.
• When you use Integer inside a string, then the Integer
is first converted into a string and then prints as a string.
$integer = 10;
$str = "$integer";
echo gettype($str); // outputs: string
➤ Using explicit Casting.
• Explicit Casting is the explicit conversion of data type because the
user explicitly defines the data type in which he wants to cast.
We will convert Integer into String.
$num = 5;
$str = (string)$num; // or String
echo gettype($str); // outputs: string
function removeElement($nums, $val) {
return array_diff($nums, [$val]);
}
print_r(removeElement([0,1,2,2,3,0,4,2], 2);
// runtime 7ms<?php
function lengthOfLastWord1($s) {
$words = str_word_count($s,1); //returns words in array
//(function returns an array with the words from the string)
$wordCount = str_word_count($s); //counts words in text
$lastW = $words[$wordCount-1];//returns last word
$lastWLen = strlen($lastW); //The last word length
$lastResult = "The last word is ".'"'.$lastW.'"'." with length $lastWLen";
return $lastWLen;
return $lastResult;