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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles