Home Backend Development PHP Tutorial Several functional codes you need to master when getting started with PHP_PHP Tutorial

Several functional codes you need to master when getting started with PHP_PHP Tutorial

Jul 21, 2016 pm 02:52 PM
body co for head html php title code example getting Started several kinds Function cycle master of classic need

Classic loop example


Classic loop example


for($counter = 1; $counter <= 6; $counter++) //Loop 6 times
{
                                                                                                                                                        print("counter is  $counter
n");                                     }  
?>




Advanced use of for

Advanced uses for


/*
​ ** Print necessary description text
*/
Print("How many days until Monday?n");
Print("

    n");
    for($currentDate = date("U"); //Define $currentDate time format
    Date("l", $currentDate) != "Monday"; //Determine whether the current system time is Monday
    $ Currentdate+= (60*60*24)) // Add 1 day
    {
                  /*                                               ** Print time name           */
    print("
  1. " . date("l", $currentDate) . "n");
    }  
    Print("
n");
?>




Simple call of function:

Simple function



Function printBold($inputText) //Define function printBold()
{
                                                                                                                       Print }  
Print("This line is not emphasized!
n"); //Print the string directly
printBold("This line is aggravated!!!"); //Call function printBold() function
Print("
n");
Print("This line is not emphasized!
n"); //Print the string directly
?>





Function with return value


Function with return value


Function makeBold($inputText) //Define function makeBold() function
{
         $boldedText = "";
         $boldedText .= $inputText;
         $boldedText .= "
";
         return($boldedText);                                                                                                                                              .}  
Print("This line is not emphasized!!!
n"); //Print the string directly
Print(makeBold("This line is emphasized!!!") . "
n");//Call function makeBold() function
Print("This line is not emphasized!!!
n"); //Print the string directly
?>




Function with default parameters


Function with default parameters



Function printColored($Text, $Color="black") //Define function function
{
                                                                                                                                                                                                                       Get the content and color of the string
}  
printColored("This is a black word!"); //Call function
Print("

n");
printColored("This is a blue word!", "blue"); //Call function
Print("
n");
?>




Use recursive algorithm to determine whether it is an integer


Judge integers


Function checkInteger($Number)
{
If($Number > 1)
                                      {
                    /* An integer minus 1 is still an integer */
                return(checkInteger($Number-1));
          }
        elseif($Number < 0)
                                      {
                     /* For a negative number, */
                                                                                                                                                                                                                                        to  /* can be analyzed for its absolute value*/
              return(checkInteger((-1)*$Number-1));//Take the absolute value and analyze negative numbers as integers
          }
        else
                                      {
If(($Number > 0) AND ($Number < 1))
                                                                   Return("Of course not");
                                                                               else
                                                                   /*0 and 1 are integer*/
/*According to the relevant mathematical definition*/
Return("Yes");
                                                                          }
}  
Print("Is 0 an integer?" .
                                                                                                                                                                                                                                                                            checkInteger (0) . "
n"); Print("Is 7 an integer? " .
           checkInteger(7) . "
n");
print("What about 3.5?" . checkInteger(3.5) . "
n");
print("What about -5?" . checkInteger(-5) . "
n");
print("And -9.2?" . checkInteger(-9.2) . "
n");
?>


Initialize array


Initializing array


$monthName = array(1=>"January", "February", "March",//Initialize an array
"April", "May", "June", "July", "August",
"September", "October", "November", "December");
Print(""May" in English is $monthName[5] .
n");//Print the 6th element in the array
?>




Get the elements in the array


Get elements in the array

$monthName = array(
/*Define $monthName[1] to $monthName[12]*/
​ ​ 1=>"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December",
/*Define $monthName["Jan"] to $monthName["Dec"]*/
"Jan"=>"January", "Feb"=>"February",
"Mar"=>"March", "Apr"=>"April",
"May"=>"May", "Jun"=>"June",
"Jul"=>"July", "Aug"=>"August",
"Sep"=>"September", "Oct"=>"October",
"Nov"=>"November", "Dec"=>"December",
/*Define $monthName["Jan"] to $monthName["Dec"]*/
"January"=>"January", "February"=>"February",
"March"=>"March", "April"=>"April",
"May"=>"May", "June"=>"June",
"July"=>"July", "August"=>"August",
"September"=>"September", "October"=>"October",
"November"=>"November", "December"=>"December"
);
/*Print related elements*/
print("Month 5 is " . $monthName[5]. "
n");
print("Month Aug is " . $monthName["Aug"] . "
n");
print("Month June is " . $monthName["June"] . "
n");
?>



Create a multidimensional array


Create a multidimensional array

$Cities = array( "North China"=>array(
"Beijing City",
"Tianjin City",
"Shijiazhuang"
),
"Northwest Region"=>array(
"Xi'an",
"Lhasa"
)
);
print("North China: ".$Cities["North China"][0]); //Print $Cities["North China"][0]
?>




PHP 4.0 realizes table-like printing

Realize table-like printing


/*
​ ** Data tabulation
*/
Print("

n"); // Table starts
for($Row=1; $Row <= 12; $Row ++)
{
​​​​print("n"); //Start line

             // do each column
for($Column=1; $Column <= 12; $Column ++)
                                      {
​​​​​​print("");
        } 
           print("n"); // End of line
}  
Print("
");//Start column
​​​​​​print($Row *$Column);//Product of table elements
Print("
n"); // End of table
?>




View some variables of the system

View PHP environment variables


Print("The name of the file you are using is: ");
Print(__FILE__);
Print("
n");
Print("
");
Print("Your operating system is: ");
Print(PHP_OS);
Print("
");
Print("Your php version is: ");
Print(PHP_VERSION)
?>




Open local or remote file

Open local or remote file


Print("

Open file via http protocol

n");
// Open the file via http protocol
If(!($myFile = fopen("d:web/web/php/test/data.txt", "r")))
{
​​​​print("File cannot be opened");
exit;
}  
While(!feof($myFile)) //Loop
{
                                                                                                                                                                                     $myLine = fgetss($myFile, 255);
​​​​print("$myLine
n");
}  
//Close the file handle
fclose($myFile);
?>




Comparison of several ways to open files

Read file content


//Open the file and print every character of the file
If($myFile = fopen("data.txt", "r"))
{
While(!feof($myFile))
{
         $myCharacter = fgetc($myFile);
          print($myCharacter);
}  
fclose($myFile);
}  
?>
");?>
//Open the file and print each line of the file
If($myFile = fopen("data.txt", "r"))
{
​​​​while(!feof($myFile))
                                                                                 $myLine = fgets($myFile, 255);
Print($myLine);
           }
fclose($myFile);
}  
?>
");?>
/* Open the file and print each line of the file,
At the same time, remove the HTML language in the retrieved string
*/
If($myFile = fopen("data.txt", "r"))
{
​​​​while(!feof($myFile))
                                                                                  $myLine = fgetss($myFile, 255);
Print($myLine);
           }
           fclose($myFile);
}  
?>




Access common file properties

Access common file properties




Print("Owner of file (UID value):");
Print(fileowner("data.txt")."
");
Print("File size:");
Print(filesize("data.txt")."
");
Print("File type:");
Print(filetype("data.txt")."
");
?>


Calling text file content


Calling text file content



// Open the file and print each line
$myFile = file( "data.txt");
for($index = 0; $index < count($myFile); $index++)
{
​​​​print($myFile[$index]."
");
}  
?>




Create directory function


Create directory function


If(mkdir("myDir1", 0777)) //Function to create a directory
{
Print ("Successful directory creation"); // The directory establishes successful
}  
else
{
Print ("Directory establishment failed!"); // The establishment of the directory failed
}  
?>



Browse catalog


Browse Catalog


//Use the table to browse the structure of the directory
Print("n");
//Create the header of the table
Print("n");
Print("
n");
Print("
n");
Print("
n");
$myDirectory = opendir("."); // Create a handle to the operating directory
// Read each sub-item in the directory
While($entryName = readdir($myDirectory))
{
​​​​print("");
              print("");
Print("");
            print("n");
}  
                                                                                                                            Print("
File nameFile size
$entryName");
​​​​print(filesize($entryName));
Print("
n");
?>




PHP related information

PHP related information


phpinfo();
?>




Commonly used numerical judgment functions

Commonly used numerical judgment functions


//Judgment array
$colors = array("red", "blue", "green");
If(is_array($colors))
{
print("colors is an array"."
");
}  
//Double precision number judgment
$Temperature = 15.23;
If(is_double($Temperature))
{
print("Temperature is a double"."
");
}  
//Integer judgment
$PageCount = 2234;
If(is_integer($PageCount))
{
print("$PageCount is an integer"."
");
}  
//Object judgment
class widget
{
      var $name;
      var $length;
}  
$thing = new widget;
If(is_object($thing))
{
​​​​print("thing is an object"."
");
}  
//Character judgment
$Greeting = "Hello";
If(is_string($Greeting))
{
print("Greeting is a string"."
");
}  
?>



File upload interface


File upload interface


if($UploadAction){
$UploadAction=0;
$TimeLimit=60;                                         /*Set the timeout limit time. The default time is 30s. When set to 0, it is unlimited */
set_time_limit($TimeLimit);
If(($Upfile != "none")&&
($Upfile != ""))
{
$Filepath="d:webwebphptest"; //Upload file storage path
$FileName=$Filepath.$Upfile_name;
if($Upfile_size <1024)                                                                                                                                     {$FileSize = (string)$Upfile_size . "Bytes";}
elseif($Upfile_size <(1024 * 1024))
{
$FileSize = number_format((double)($Upfile_size / 1024), 1) . " KB";
}
else
{
$FileSize = number_format((double)($Upfile_size/(1024*1024)),1)."MB";
}
if(!file_exists($FileName))
{
if(copy($Upfile,$FileName))
{unlink($Upfile);
echo "

n"; echo "File $Upfile_name has been uploaded successfully!";
echo "

n";
echo "File location: $FileName";
echo "

n";
echo "File size: $FileSize";
echo "

n";
}
else
{echo "File $Upfile_name upload failed!"; }
}
else
{echo "File $Upfile_name already exists!"; }
}
else
{echo "You did not select any files to upload!"; }
set_time_limit(30); ​ ​  }
?>
ACTION = "default.php" METHOD = "POST"> 
 
 
 
 


 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/371530.htmlTechArticle经典循环例子 HTML HEAD TITLE经典循环例子/TITLE /HEAD BODY ? for($counter=1;$counter=6;$counter++)//循环6次 { print(Bcounteris$counter/BBRn);//打印6次 } ? /BODY /H...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles