PHP Custom Function + System Function Library

global variable

    $n = 5; //global variable
    function fun1(){
        global $n;
        echo 'I can also call global variables within a function body n,Its value is:' , $n;//5
        $n++;
    }
    fun1();
    echo '<hr>';
    echo $n;//6
    $n = 6;
    function fun1(){
        echo 'The value of the variable is:' , $GLOBALS['n'];
        $GLOBALS['n']++;
    }
    fun1();
    echo $GLOBALS['n'];

Calculate the sum of 1~100 without looping statements

    function recursive($n){
        if($n>=1){
            return $n + recursive($n-1);
        }
    }
    echo recursive(100);

Quote

    $foo = 'Bob';
    $bar = &$foo; //Aliases treated as variables
    $bar = 'Rose';
    echo $foo;//Rose

    $foo = 'Mooc';
    $bar = &$foo; //Aliases treated as variables
    unset($foo); //Variable Destroy
    echo $bar;//Mooc

Custom Functions

    function fun1(&$n){
        $n++;
        echo 'I am a local variable within a function' ,  $n ;//4
    }

    $n = 3;
    fun1($n);
    echo $n , '<hr>';//4

Get Extensions

    function getExtension($filename)
    {
        $pos = strrpos($filename, '.');
        $extension = strtolower(substr($filename, $pos + 1));
        return $extension;
    }

    $path = 'mooc.func.pHP';
    var_dump(getExtension($path));

Average

    function avg(...$args)
    {
        return $args;
    }
    var_dump(avg(1, 2, 3));

System Function Library

String to Array

    $str = 'A|B|C|D';
    $arr = explode('|', $str);
    print_r($arr);//[A,B,C,D]

Array to String

    $arr2 = array('Tom','John','Rose');
    $str2 = implode(',',$arr2);
    echo $str2;//Tom,John,Rose

Get the extension:
Method One

    $filename = 'ab.cd.gif.JpEg'; //gepj.fig.dc.ba
    $num = strrpos($filename, '.');
    echo strtolower(substr($filename, $num+1)) , '<br/><br/>';//jpeg

Method 2

    $filename = 'ab.cd.gif.JpEg'; //gepj.fig.dc.ba
    $str2 = strrev($filename);//strrev strrev
    $num = strpos($str2, '.');
    echo strtolower(strrev(substr($str2, 0,$num)));//jpeg

trim removes characters on both sides of a string

    $str = "\n\n\t\tABC\t\t";
    echo trim($str);//ABC

md5() encryption

    $str = 'abc';
    echo md5($str);//900150983cd24fb0d6963f7d28e17f72

format string

    $number = 5;
    $str = 'shanghai';
    $txt = sprintf('there are %d million cars in %s',$number,$str);
    echo $txt;//there are 5 million cars in shanghai

    $number = 123;
    $txt = sprintf("The result with two decimal places is:%1\$.2f,\n Yes without decimals:%1\$d",$number);
    echo $txt;//The result with two decimal places is:123.00,Yes without decimals:123

htmlspecialchars special characters to HTML entities

    $str = "A>B,B<C,Tom&John,He said:\"I'm OK\"";
    echo htmlspecialchars($str,ENT_QUOTES);//A&gt;B,B&lt;C,Tom&amp;John,He said:&quot;I&#039;m OK&quot;

Conversion via str_replace

    $str1 = str_replace('&', '&amp;', $str); //Must be the first step
    $str2 = str_replace('>', '&gt;', $str1);
    $str2 = str_replace('<', '&lt;', $str2);
    $str2 = str_replace('"', '&quot;', $str2);
    $str2 = str_replace('\'', '&#39;', $str2);
    echo $str2;//A&gt;B,B&lt;C,Tom&amp;John,He said:&quot;I&#039;m OK&quot;

str_ireplace is case insensitive

    $str = 'javascript';
    echo str_ireplace('A', 'b', $str);//jbvbscript

Randomly shuffle all characters in a string

    $str = 'abcdefghijklmnopqrstuvwxyz';
    $str = str_shuffle($str);
    echo substr($str,0,4);//drif

strlen gets character length

    $str1 = NULL;//0
    $str2 = 'AB';//2
    $str3 = 'China';//6 3 characters per Chinese
    echo strlen($str1) , strlen($str2) , strlen($str3);

Strios is case-insensitive, strings are numbered from 0, and FALSE is returned if they do not appear

    $str1 = 'javascript';
    $str2 = 'A';
    var_dump(stripos($str1, $str2)); //int(1)  

Searches for the position of $str2 in the string and returns all characters from that position to the end of the string

    $str1 = 'abcdcef';
    $str2 = 'c';
    echo strrchr($str1, $str2);//cef

Get Extensions

    $filename = 'a.bc.cd.png';
    echo substr(strrchr($filename, '.'),1);//png

strtoupper uppercase
strtolower to lowercase

    $str1 = 'html';
    $str2 = 'PHP';
    echo strtoupper($str1) , strtolower($str2);//HTMLphp

Capitalize the first letter of a ucfirst sentence
Uppercase ucwords

    $str3 = 'this is a test';
    echo ucfirst($str3) , ucwords($str3);

substr intercept string
Negative = String Length + Negative

    $str = 'javascript';
    echo strlen($str);//10
    echo substr($str, 0,4) ;//java
    echo substr($str, 4);//script
    echo substr($str, -2);//pt   -2=10-2=8
    echo substr($str, -5,-2) , "\n";//cri   -5,-2=5,8

Convert string to Zend_Controller_Front

    $str = 'ZenD_CONTRollER_FronT';
    //1.Convert lowercase
    $str1 = strtolower($str);
    //2.Replace underscores with spaces
    $str2 = str_replace('_', ' ', $str1);
    //3.adopt ucwords Capitalize the first letter
    $str3 = ucwords($str2);
    //4.Replace spaces with underlines
    $str4 = str_replace(' ', '_', $str3);
    echo $str4;//Zend_Controller_Front

floor() ceil()

    $x = 2.7;
    $y = 3.01;
    echo floor($x) , '<br/><br/>';//2 Rounding Down
    echo ceil($y) , '<br/><br/>';//4 ceil

Assuming X records, Y records per page, total number of pages z

    z = ceil(X/Y);

fmod() modulo floating point numbers

    echo fmod(7.8,3) , '<br/>';//1.8

Modulating Integers

    echo 7.8 % 3 ; //Operation of integer remainder//1

Formatting Numbers

    $x = 7896.827;
    echo number_format($x) , '<br/><br/>';//7,897
    echo number_format($x,2) , '<br/><br/>';//7,896.83

pow() power operation sqrt() square root operation

    echo pow(2,3);//8
    echo sqrt(4) ;//2

mt_rand() is a better random number generator because it sows a better random number seed than rand(); and its performance is four times faster than rand().

    echo rand(50,80);
    echo mt_rand(10,99);

Generate a four-digit random validation code

    $chars = 'abcdefghijlmnopqrstuvwxyz789654321';
    $len = strlen($chars);
    for($i=0;$i<4;$i++){
        $char .= substr($chars,mt_rand(0,$len-1),1);
    }
    echo $char;

round() rounding

    $x = 7.238;
    echo round($x);//7
    echo round($x,2);//7.24

strtotime string conversion time

    echo 'current date:'  , date('Y-m-d') , "\n";//2020-01-10
    echo 'Date of next month:' , date('Y-m-d', strtotime('1 month')) , "\n";//2020-02-10
    echo 'Last day of last month:' , date('Y-m-d H:i:s',strtotime('last day of -1 month')) , "\n";//2019-12-31 10:39:12
    echo 'Zero on last day of last month:' , date('Y-m-d H:i:s', strtotime("midnight last day of -1 month")) , "\n"; //2019-12-31 00:00:00
    echo 'Yesterday at 0:00:' ,  date('Y-m-d H:i:s',strtotime('yesterday')) , "\n";//2020-01-09 00:00:00
    echo 'Now?' ,  date('Y-m-d H:i:s',strtotime('now')) , "\n";//2020-01-10 10:39:12
    echo 'The timestamp between three weeks is:' ,  strtotime('-3 weeks');//The timestamp between three weeks is:1576810790
    echo (time() -  strtotime('-3 weeks'))/86400 ;//21  Interval Time
    echo 'Last month:'.date('Y-m-d H:i:s',strtotime('-1 month')) ; //Last month: 2019-12-10 10:59:50
    echo 'On the first day of last month:'.date('Y-m-d H:i:s',strtotime('first day of -1 month'));//First day of last month: 2019-12-01 10:59:50

Returns the date/time information for the current local date/time

    print_r(getdate());
    //Array
    //(
    //    [seconds] => 3
    //    [minutes] => 42
    //    [hours] => 10
    //    [mday] => 10
    //    [wday] => 5
    //    [mon] => 1
    //    [year] => 2020
    //    [yday] => 9
    //    [weekday] => Friday
    //[month] => January
    //[0] => 1578624123
    //)

microtime() returns the number of microseconds of the current Unix timestamp

    echo microtime();//0.41369400 1578624195

When set to TRUE, specifies that the function should return a floating point number or a string; defaults to FALSE

    echo microtime(true);//1578624195.4137

Calculate program run time

    $start = microtime(true);
    $sum = 0;
    for ($i=0; $i <1000000 ; $i++) { 
        $sum += $i;
    }
    $end = microtime(true);
    echo  'Total expenses' , round($end - $start,3) , 'second';//Total cost 0.016 second

time()

    echo time() ;//1578625294
    echo 'The current date and time is:' , date('Y-m-d H:i:s') ;//The current date and time is:2020-01-10 11:01:34
    echo 'Yesterday's date time was:' , date('Y-m-d H:i:s',time()-86400) ; //24*60*60 //Yesterday's date is: 2020-01-09 11:01:34

The uniqid() function generates a unique ID based on the current time in microseconds

    echo uniqid();//5e17e94f8a19b
    echo uniqid('abc');//abc5e17e96c1771e
    echo uniqid(microtime());//0.09603300 15786253885e17e96c17727
    echo uniqid(microtime() . mt_rand()); //mt_rand(100,999);//0.09604200 15786253884744704985e17e96c1772f

    //uuid 8-4-4-4-12 = 32
    echo md5(uniqid(microtime() . mt_rand()));//cf6333288fcb04f60fbbedafd127201e

session

    session_start();
    echo session_id();//bp99jhu204h6vi214ttgcjce80

Tags: PHP Javascript Java Unix

Posted on Thu, 09 Jan 2020 22:56:56 -0500 by dantone