Posts

Showing posts from March, 2019

Echoing a function that echoes and returns values in PHP

<?php function print_name() {     echo 'Name';     return 'World'; } echo 'Hello'.print_name(); /* Output: Name Hello World */ ?>

Echoing a function that echoes something and returns nothing in PHP

<?php function print_name() {     echo 'Name'; } echo 'Hello'.print_name().' World.'; /* Output: Name Hello World */ ?>

Timestamps in PHP

<?php echo date('h:i:s a', time() + 5 * 3600).'<br/>'; // added 5 hours to current time echo date('h:i:s a', strtotime('5 hours')).'<br/>'; // added 5 hours to current time $timestamp = mktime(0, 40, 30, 2, 11, 95); // made own time echo 'Time: '.date('h:i:sa', $timestamp).'<br/>'; // Time: 12:40:30am echo 'Date: '.date('d/m/Y', $timestamp).'<br/>'; // Date: 11/02/1995 $timestamp = mktime(12, 40, 30, 2, 11, 95); echo 'Time: '.date('h:i:sa', $timestamp).'<br/>'; // Time: 12:40:30pm $timestamp = mktime(13, 40, 30, 2, 11, 95); echo 'Time: '.date('h:i:sa', $timestamp).'<br/>'; // Time: 01:40:30pm ?>

Rolling a dice in PHP

<?php if(isset($_POST['roll'])) {     echo 'You rolled a '.rand(1, 6).'<br/><br/>'; } ?> <form action="index.php" method="post">     <input type="submit" name="roll" value="Roll Dice"/> </form>

Replace every instance of a substring in PHP

<?php if(isset($_GET['submit'])) {     if(strlen($_GET['text']) && strlen($_GET['search_for']) && strlen($_GET['replace_with']))     {         $text = $_GET['text'];         $search_for = $_GET['search_for'];         $replace_with = $_GET['replace_with'];         $offset = 0;         $search_for_length = strlen($search_for);         $replace_with_length = strlen($replace_with);         $text = ' '.$text; // that's how search position will never be 0                 while($search_for_position = strpos($text, $search_for, $offset))         {             $text = substr_replace($text, $replace_with, $search_for_position, $search_for_length);             $offset = $search_for_position + $replace_with_length; // that's how $search_for will not be found in $replace_with when $search_for actualy exists in $replace_with         }                 echo $text.'<hr/>';     }     else     {    

How '0' becomes a false value in PHP

<?php if('0') {     echo 1; } else {     echo 0; } // outputs 0, because 'if' statement needs to convert '0' into boolean type value to work and in PHP (bool)'0' creates boolean false if('0' == false) // because of loose comparison '0' will be converted into boolean type automatically {     echo 1; } else {     echo 0; } //ouputs 1 if('0' === false) {     echo 1; } else {     echo 0; } // outputs 0, because '0' is a string after all and false is boolean, so their type didn't match here and for strict comparison no type conversion happened ?>

How to find all occurrence position of a substring in PHP

<?php $string = 'ab cd ab cd ab'; $string = ' '.$string; // because the while loop below won't run if we find the first match in position 0 $find = 'ab'; $find_length = strlen($find); $offset = 1; // from this index the search of $find will start // strpos function returns false when offset value equals to string length, but returns error for more than that while($find_position = strpos($string, $find, $offset)) {        echo '<b>'.$find.'</b> is found at '.$find_position.'<br/>';         $offset = $find_position + $find_length; } ?>

How to count the characters of a string in PHP

<?php $string = 'hello 0'; for($i = 0; @$string[$i] || @$string[$i] == '0'; $i++); /* $string[$i] echoes an error message when $i = 7 and  @ (error control operator) hides that error. When the error occurs $string[$i] = Null because $i is undefined index number. Second condition is used here to treat '0' as a true value */ echo $i; // outputs 7 ?>

What exactly global keyword does in PHP

<?php $x = 1; // here I defined global variable x, now $_GLOBALS['x' => 1] function my_function() {       echo $x; // outputs a notice that says 'Undefined variable: x', because php functions don't access global variables directly, but through reference        $x = 2; // here I defined local variable x        echo $x; // outputs 2        global $x; // Now the local variable x has got the reference of the global variable x that means 'globals $x' statement equals to $x = &$_GLOBALS['x']. If there was no global variable named x then a global variable named x would be created containing null as its value and the local variable x would have its reference as value.        echo $x; // outputs 1 } my_function(); ?>

Unquoted text as a variable value in PHP

<?php $animal = CAT; // outputs Notice: Use of undefined constant cat - assumed 'cat' echo $animal; // ouputs CAT define('CAT', '4 legs'); $animal = CAT; echo $animal; // outputs 4 legs /* conclusion: undefined constant name and unquoted string value will be converted into string automatically */ ?>

How to execute same block of codes for multiple cases of Switch statement in PHP

<?php $day = 'Saturday'; switch($day) {     case 'Saturday':     case 'Sunday':         echo 'It\'s a weekend';     break;         default:         echo 'Not a weekend';     break; } ?>

How to use comparison operators in switch statement in PHP

<?php $number = 27; switch(true) {     case ($number > 100):         echo 'Bigger than hundred';     break;        case ($number < 100):         echo 'Lower than hundred';     break;        default:         echo 'Equal to hundred';     break; } ?>

Comparing a number with a string that contains number in PHP

<?php if(12 == '12a1') // '12a1' will be converted into 12 {     echo 'True'; } else {     echo 'False'; } // outputs True if(12 == 'a121') // here 'a121' will be converted into 0, because of non-numerical character up front {     echo 'True'; } else {     echo 'False'; } // outputs False if(12.5 == '12.5a') // here '12.5a' will be converted into 12.5 {     echo 'True'; } else {     echo 'False'; } // outputs True ?>

Increment and Decrement of a string in PHP

<?php $string = 'abc'; echo $string; // outputs abc $string++; echo $string; // outputs abd $string++; echo $string; // outputs abe ++$string; echo $string; // outputs abf ++$string; echo $string; // outputs abg $string--; echo $string; // outputs abg $string--; echo $string; // outputs abg --$string; echo $string; // outputs abg --$string; echo $string; // outputs abg /* Decrement operator doesn't have any effect on string but increment operator increases the last character of the string. If we use increment operator when the last character of a string is Z or, z then the the last character will be A or, a respectively. */ ?>

Secret of post increment in PHP

<?php $x = 1; $x = ($x++) + 1; // This statement equals to $x = 1 + 1, here $x++ statement puts the value of $x in its place and then execute itself. After that, $x = ($x++) + 1 which means $x = 1 + 1 is executed. echo $x; // outputs 2 ?>

Number and String comparison in PHP (Numeric Values VS String Values)

<?php if(0 == 'Cat') {     echo 1; } // outputs 1 if(0.1 > 'Cat') {     echo 1; } // outputs 1 # strings are converted into 0 when strings are compared (using '==' operator) with numeric values ?>

String comparison in PHP (Capital Letter VS Small Letter)

<?php if('cat' == 'Cat') {     echo 1; } else if('cat' > 'Cat') {     echo 2; } else {     echo 3; } // outputs 2 # (a to z) is bigger than (A to Z) ?>

That happens when we concatenate numbers in PHP

<?php echo 10 . 3; // outputs 103, here 10 & 3 converted into strings echo 'Ten' . 3; // outputs Ten3, here 3 converted into string echo 10 . 'Three'; // outputs 10Three, here 10 converted into string // Concatenation Operator (.) is used to add two strings, not float or integer. ?>

False values in PHP

<?php if('') {     echo 'True'; } else {     echo 'False'; } // outputs False if(0) {     echo 'True'; } else {     echo 'False'; } // outputs False if(null) {     echo 'True'; } else {     echo 'False'; } // outputs False ?>