如何在 PHP 中编写注释

Answer: Use the Syntax “// text” and “/* text */”

Comments are usually written within the block of PHP code to explain the functionality of the code. It will help you and others in the future to understand what you were trying to do with the PHP code. Comments are not displayed in the output, they are ignored by the PHP engine.

Single Line Comments

PHP single line comment begins with //, See the example below:

<?php
    echo "Hello World!"; // Output "Hello World!"
?>

Multi-line Comments

PHP multi-line line comment begins with /*, and ends with */.

<?php
    /* The following line of code
       will output the "Hello World!" message */
    echo "Hello World!";
?>

如何在 PHP 中删除字符串中的空格

Answer: Use the PHP trim() function

You can use the PHP trim() function to remove whitespace including non-breaking spaces, newlines, and tabs from the beginning and end of the string. It will not remove whitespace occurs in the middle of the string. Let’s take a look at an example to understand how it basically works:

<?php
$my_str = '    Welcome to Tutorial Republic ';
echo strlen($my_str); // Outputs: 33

$trimmed_str = trim($my_str);
echo strlen($trimmed_str); // Outputs: 28
?>

如何在 PHP 中查找字符串中的字符数

Answer: Use the PHP strlen() function

You can simply use the PHP strlen() function to find the number of characters in a string of text. It also includes the white spaces inside the specified string.

Let’s take a look at the following example to understand how it basically works:

<?php
$my_str1 = 'The quick brown fox jumps over the lazy dog.';
echo strlen($my_str1); // Outputs: 44

$my_str2 = '    The quick brown fox jumps over the lazy dog. ';
echo strlen($my_str2); // Outputs: 49
?>

如何在 PHP 中查找字符串中的单词数

Answer: Use the PHP str\_word\_count() function

PHP str\_word\_count() 函数可用于查找字符串中的单词数。

让我们通过一个示例来了解该函数的基本工作原理:

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';

// Outputs: 9
echo str_word_count($my_str);
?>

如何在 PHP 中删除字符串中的特殊字符

Answer: Use the PHP htmlspecialchars() function

Certain characters such as (&, ", ', <, >) have special significance in HTML, and should be converted to HTML entities. You can use the PHP htmlspecialchars() function to convert special characters in a string to HTML entities. Let’s check out an example:

<?php
$my_str = "String with <b>special</b> characters.";

// Removing HTML special characters
echo htmlspecialchars($my_str);
?>

If you view the source code of the output you will the string “String with special characters.” converted to “String with special characters.”

如何在 PHP 中替换字符串中的一个单词

Answer: Use the PHP str\_replace() function

You can use the PHP str\_replace() function to replace all the occurrences of a word within a string.

In the following example the word “facts” is replaced by the word “truth”.

<?php
$my_str = 'If the facts do not fit the theory, change the facts.';

// Display replaced string
echo str_replace("facts", "truth", $my_str);
?>

The PHP str\_replace() function is case-sensitive, however if you want to perform case-insensitive match and replace you can use the str\_ireplace() function.

如何在 PHP 中对字符串前面追加

Answer: Use the PHP Concatenation Operator

There is no specific function to prepend a string in PHP. But you can use the PHP concatenation operator (.) to prepened a string with another string.

Let’s take a look at the following example to understand how it basically works:

<?php
$a = "Hello";
$b = "World!";
$b = $a . " " . $b;
echo $b; // Outputs: Hello World!
?>

See the tutorial on PHP operators to learn about the operators in detail.

如何在 PHP 中从字符串中提取子串

Answer: Use the PHP substr() function

The PHP substr() function can be used to get the substring i.e. the part of a string from a string. This function takes the start and length parameters to return the portion of string.

Let’s check out an example to understand how this function basically works:

<?php
$str = "Hello World!";
echo substr($str, 0, 5);  // Outputs: Hello
echo substr($str, 0, -7); // Outputs: Hello
echo substr($str, 0);     // Outputs: Hello World!
echo substr($str, -6, 5); // Outputs: World
echo substr($str, -6);    // Outputs: World!
echo substr($str, -12);   // Outputs: Hello World!
?>

如何在 PHP 中比较两个字符串

Answer: Use the PHP strcmp() function

You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2; returns > 0 if str1 is greater than str2, and 0 if they are equal.

Let’s check out an example to understand how this function basically works:

<?php
$str1 = "Hello";
$str2 = "Hello World";
echo strcmp($str1, $str2); // Outputs: -6
?>

The PHP strcmp() function compare two strings in a case-sensitive manner. If you want case-insensitive comparison, you can use the strcasecmp() function.

如何在 PHP 中获取当前页面的 URL

Answer: Use the PHP $\_SERVER Superglobal Variable

You can use the $\_SERVER built-in variable to get the current page URL in PHP. The $\_SERVER is a superglobal variable, which means it is always available in all scopes.

Also if you want full URL of the page you’ll need to check the scheme name (or protocol), whether it is http or https. Let’s take a look at an example to understand how it works:

<?php
$uri = $_SERVER['REQUEST_URI'];
echo $uri; // Outputs: URI

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $url; // Outputs: Full URL

$query = $_SERVER['QUERY_STRING'];
echo $query; // Outputs: Query String
?>

如何在 PHP 中通过连接数组值创建字符串

Answer: Use the PHP implode() or join() function

You can use the PHP implode() or join() function for creating a string by joining the values or elements of an array with a glue string like comma (,) or hyphen (-).

Let’s take a look at the following example to understand how it basically works:

<?php
$array = array("red", "green", "blue");

// Turning array into a string
$str = implode(", ", $array);
echo $str; // Outputs: red, green, blue
?>

如何在 PHP 中将字符串拆分为数组

Answer: Use the PHP explode() function

You can use the PHP explode() function to split or break a string into an array by a separator string like space, comma, hyphen etc. You can also set the optional limit parameter to specify the number of array elements to return. Let’s try out an example and see how it works:

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
print_r(explode(" ", $my_str));
echo "<br>";
print_r(explode(" ", $my_str, 4));
?>

如何在 PHP 中合并两个字符串

Answer: Use the PHP Concatenation Operator

You can use the PHP concatenation operator (.) to combine or join two strings together in PHP. This operator is specifically designed for strings. Let’s see how it works:

<?php
$str1 = 'Hello';
$str2 = 'World!';
$new_str = $str1 . ' ' . $str2;
echo $new_str; // Outputs: Hello World!
?>

如何在 PHP 中把字符串转换成小写字母

Answer: Use the PHP strtolower() function

You can use the PHP strtolower() function to convert a string to lowercase.

Let’s check out the following example to understand how this function actually works:

<?php
$my_str = 'The Quick Brown Fox Jumps Over The Lazy Dog.';
echo strtolower($my_str);
?>

如何在 PHP 中把字符串转换成大写字母

Answer: Use the PHP strtoupper() function

You can use the PHP strtoupper() function to convert a string to uppercase.

Let’s try out the following example to understand how this function basically works:

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
echo strtoupper($my_str);
?>

如何在 PHP 中把字符串的第一个字母转换成大写字母

Answer: Use the PHP ucfirst() function

You can use the PHP ucfirst() function to change the first character of a string to uppercase (i.e. capital). Alternatively, you can use the strtolower() function in combination with the ucfirst() function, if you want to make only first letter of the string to uppercase and rest of the string to lowercase. Let’s check out an example to understand how it works:

<?php
$str1 = 'the color of the sky is blue.';
echo ucfirst($str1);
echo "<br>";
$str2 = 'the Color of the Sky is Blue.';
echo ucfirst(strtolower($str2));
?>

如何在 PHP 中把特殊的 HTML 实体转换回字符

Answer: Use the PHP htmlspecialchars\_decode() function

You can use the PHP htmlspecialchars\_decode() function to convert the special HTML entities such as &, <, > etc. back to the normal characters (i.e. &, <, >).

The htmlspecialchars\_decode() function is opposite of the htmlspecialchars() function which converts special HTML characters into HTML entities. Let’s check out an example:

<?php
$my_str = "I'll come & <b>"get you"</b>.";

// Decode &, <, > and "
echo htmlspecialchars_decode($my_str);

// Decode &, <, >, " and '
echo htmlspecialchars_decode($my_str, ENT_QUOTES);

// Decode &, < and >
echo htmlspecialchars_decode($my_str, ENT_NOQUOTES);
?>

如何在 PHP 中删除字符串开头的空格

Answer: Use the PHP ltrim() function

You can use the PHP ltrim() function to strip whitespace from the beginning of a string.

Let’s take a look at an example to understand how this function really works:

<?php
$my_str = '    Hello World!';
echo strlen($my_str); // Outputs: 16

$trimmed_str = ltrim($my_str);
echo strlen($trimmed_str); // Outputs: 12
?>

如何在 PHP 中删除字符串结尾的空格

Answer: Use the PHP rtrim() function

You can use the PHP rtrim() function to strip whitespace from the end of a string.

Let’s check out an example to understand how this function basically works:

<?php
$my_str = 'Hello World!    ';
echo strlen($my_str); // Outputs: 16

$trimmed_str = rtrim($my_str);
echo strlen($trimmed_str); // Outputs: 12
?>

如何在 PHP 中新建一行

Answer: Use the Newline Characters ‘\n’ or ‘\r\n’

You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

Let's take a look at the following example to understand how it basically works:

<?php
echo "If you view the page source \r\n you will find a newline in this string.";
echo "<br>";
echo nl2br("You will find the \n newlines in this string \r\n on the browser window.");
?>
Note: The character \n writes a newline in UNIX while for Windows there is the two character sequence: \r\n. To be on safe side use the \r\n instead.

如何在 PHP 中查找字符串长度

Answer: Use the PHP strlen() function

You can simply use the PHP strlen() function to get the length of a string. The strlen() function return the length of the string on success, and 0 if the string is empty.

Let’s take a look at the following example to understand how it actually works:

<?php
$str1 = 'Hello world!';
echo strlen($str1); // Outputs: 12
echo "<br>";

$str2 = ' Hello    world! ';
echo strlen($str2); // Outputs: 17
?>

如何在 PHP 中检查变量是否已设置

Answer: Use the PHP isset() function

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.

Let's check out an example to understand how this function basically works:

<?php
$var1 = '';
if(isset($var1)){
    echo 'This line is printed, because the $var1 is set.';
}
echo "<br>";

$var2 = 'Hello World!';
if(isset($var2)){
    echo 'This line is printed, because the $var2 is set.';
}
echo "<br>";

// Unset the variable
unset($var2);

if(isset($var2)){
    echo 'This line is printed, because the $var2 is set.';
} else {
    echo 'This line is printed, because the $var2 is not set.';
}
echo "<br>";

$var3 = NULL;
if(isset($var3)){
    echo 'This line is printed, because the $var3 is set.';
} else {
    echo 'This line is printed, because the $var3 is not set.';
}
?>

如何在 PHP 中检查变量是否为空

Answer: Use the PHP empty() function

You can use the PHP empty() function to find out whether a variable is empty or not. A variable is considered empty if it does not exist or if its value equals FALSE.

Let’s try out the following example to understand how this function basically works:

<?php
$var1 = '';
$var2 = 0;
$var3 = NULL;
$var4 = FALSE;
$var5 = array();

// Testing the variables
if(empty($var1)){
    echo 'This line is printed, because the $var1 is empty.';
}
echo "<br>";

if(empty($var2)){
    echo 'This line is printed, because the $var2 is empty.';
}
echo "<br>";

if(empty($var3)){
    echo 'This line is printed, because the $var3 is empty.';
}
echo "<br>";

if(empty($var4)){
    echo 'This line is printed, because the $var4 is empty.';
}
echo "<br>";

if(empty($var5)){
    echo 'This line is printed, because the $var5 is empty.';
}
?>
Note: The empty() function does not generate a warning if the variable does not exist. That means empty() is equivalent to !isset(var) || var == false.

如何在 PHP 中检查变量是否为NULL

Answer: Use the PHP is\_null() function

You can use the PHP is\_null() function to check whether a variable is null or not.

Let’s check out an example to understand how this function works:

<?php
$var = NULL;

// Testing the variable
if(is_null($var)){
    echo 'This line is printed, because the $var is null.';
}
?>

The is\_null() function also returns true for undefined variable. Here’s a example:

<?php
// Testing an undefined variable
if(is_null($inexistent)){
    echo 'This line is printed, because the $inexistent is null.';
}
?>

如何在 PHP 中反转字符串

Answer: Use the PHP strrev() function

You can use the PHP strrev() to reverse the text writing direction of a string.

Let’s take a look at an example to understand how it basically works:

<?php
echo strrev("Hello world!"); // Outputs: "!dlrow olleH"
?>

如何在 PHP 中用另一个字符串替换字符串的一部分

Answer: Use the PHP str\_replace() function

You can use the PHP str\_replace() function to find and replace any portion of a string with another string. In the following example the substring “quick brown fox” of the string $my\_str is replaced by the string “swift white cat”. Let’s try it out and see how it works:

<?php
$my_str = "The quick brown fox jumps over the lazy dog.";

// Display replaced string
echo str_replace("quick brown fox", "swift white cat", $my_str);
?>

如何在 PHP 中计算子串在字符串中出现的次数

Answer: Use the PHP substr\_count() function

You can use the PHP substr\_count() function to find out how many times a given substring is appears or repeated inside a string. Let’s try out an example to see how it works:

<?php
$quote = "Try not to become a man of success, but rather try to become a man of value.";

echo substr_count($quote, 'man'); // Outputs: 2
?>

如何在 PHP 中计算数组中的所有元素

Answer: Use the PHP count() or sizeof() function

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn’t set.

You can additionally use the isset() function to check whether a variable is set or not.

<?php
$days = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

// Printing array size
echo count($days);
echo "<br>";
echo sizeof($days);
?>

如何在 PHP 中打印或回显数组的所有值

Answer: Use the PHP foreach loop

There are so many ways of printing an array values, however the simplest method is using the foreach loop. In the following example we’ve iterated over the $colors array and print all its elements using the echo or print statement. Let’s try it out and see how it works:

<?php
$colors = array("Red", "Green", "Blue", "Yellow", "Orange");

// Loop through colors array
foreach($colors as $value){
    echo $value . "<br>";
}
?>

如何在 PHP 中显示数组的结构和值

Answer: Use the PHP print\_r() or var\_dump() Statement

You can either use the PHP print\_r() or var\_dump() statement to see or check the structure and values of an array in human-readable format on the screen. The var\_dump() statement however gives more information than print\_r(). Let’s see how it basically works:

<?php
$cities = array("London", "Paris", "New York");

// Print the cities array
Print_r($cities);
echo "<hr>";
var_dump($cities);
?>

如何在 PHP 中颠倒数组的顺序

Answer: Use the PHP array\_reverse() function

You can use the PHP array\_reverse() function to reverse the order of the array elements.

Let’s try out an example to understand how this function actually works:

<?php
$colors = array("Red", "Green", "Blue");

// Printing the reversed array
print_r(array_reverse($colors));
?>

如何在 PHP 中检查数组中是否存在值

Answer: Use the PHP in\_array() function

You can use the PHP in\_array() function to test whether a value exists in an array or not.

Let’s take a look at an example to understand how it basically works:

<?php
$zoo = array("Lion", "Elephant", "Tiger", "Zebra", "Rhino", "Bear");
if(in_array("Elephant", $zoo)){
    echo "The elephant was found in the zoo.";
}
echo "<br>";
if(in_array("Tiger", $zoo)){
    echo "The tiger was found in the zoo.";
}
?>

如何在 PHP 中检查数组中是否存在键

Answer: Use the PHP array\_key\_exists() function

You can use the PHP array\_key\_exists() function to test whether a given key or index exists in an array or not. This function returns TRUE on success or FALSE on failure.

Let’s take a look at the following example to understand how it actually works:

<?php
$cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York");

// Testing the key exists in the array or not
if(array_key_exists("France", $cities)){
    echo "The key 'France' is exists in the cities array";
}
?>

如何在 PHP 中删除数组中的最后一个元素

Answer: Use the PHP array\_pop() function

You can use the PHP array\_pop() function to remove an element or value from the end of an array. The array\_pop() function also returns the last value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

Let’s check out an example to understand how this function basically works:

<?php
$sports = array("Baseball", "Cricket", "Football", "Shooting");

// Deleting last array item
$removed = array_pop($sports);
print_r($sports);
echo "<br>";
var_dump($removed);
?>

如何从 PHP 数组中删除第一个元素

Answer: Use the PHP array\_shift() function

You can use the PHP array\_shift() function to remove the first element or value from an array. The array\_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

Let’s try out the following example to understand how this method works:

<?php
$hobbies = array("Acting", "Drawing", "Music", "Films", "Photography");

// Deleting first array item
$removed = array_shift($hobbies);
print_r($hobbies);
echo "<br>";
var_dump($removed);
?>

如何在 PHP 中为数组的开头添加元素

Answer: Use the PHP array\_unshift() function

You can use the PHP array\_unshift() function to insert one or more elements or values to the beginning of an array. Let’s check out an example to see how it works:

<?php
$skills = array("HTML5", "CSS3", "JavaScript");

// Prepend array with new items
array_unshift($skills, "Illustrator", "Photoshop");
print_r($skills);
?>

如何在 PHP 中为数组的末尾添加元素

Answer: Use the PHP array\_push() function

You can use the PHP array\_push() function to insert one or more elements or values at the end of an array. Let’s try out an example and see how this function works:

<?php
$skills = array("HTML5", "CSS3", "JavaScript");

// Append array with new items
array_push($skills, "jQuery", "PHP");
print_r($skills);
?>

如何在 PHP 中把两个或多个数组合并成一个数组

Answer: Use the PHP array\_merge() function

You can use the PHP array\_merge() function to merge the elements or values of two or more arrays together into a single array. The merging is occurring in such a way that the values of one array are appended to the end of the previous array. Let’s check out an example:

<?php
$array1 = array(1, "fruit" => "banana", 2, "monkey", 3);
$array2 = array("a", "b", "fruit" => "apple", "city" => "paris", 4, "c");

// Merging arrays together
$result = array_merge($array1, $array2);
print_r($result);
?>
Note: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one during the merging process.

如何在 PHP 中按字母顺序对数组值排序

Answer: Use the PHP sort() and rsort() function

The PHP sort() and rsort() functions can be used for sorting numeric or indexed arrays. The following sections will show you how these functions basically work:

Sorting Numeric Arrays in Ascending Order

You can use the sort() function for sorting the numeric array elements or values alphabetically or numerically in the ascending order. Let’s try out an example to see how it works:

<?php
$text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon");
$numbers = array(1, 2, 3.5, 5, 8, 10);

// Sorting the array of string
sort($text);
print_r($text);
echo "<br>";

// Sorting the array of numbers
sort($numbers);
print_r($numbers);
?>

Sorting Numeric Arrays in Descending Order

You can use the rsort() function for sorting the numeric array elements or values alphabetically or numerically in the descending order. Let’s check out an example:

<?php
$text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon");
$numbers = array(1, 2, 3.5, 5, 8, 10);

// Sorting the array of string
rsort($text);
print_r($text);
echo "<br>";

// Sorting the array of numbers
rsort($numbers);
print_r($numbers);
?>

如何在 PHP 中删除数组中的重复值

Answer: Use the PHP array\_unique() function

You can use the PHP array\_unique() function to remove the duplicate elements or values form an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys. Here’s an example:

<?php
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");

// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
?>

如何在 PHP 中随机调整数组的顺序

Answer: Use the PHP shuffle() function

You can use the PHP shuffle() function to randomly shuffle the order of the elements or values in an array. The shuffle() function returns FALSE on failure.

Let’s try out the following example to understand how this function basically works:

<?php
// Creating an array containing a range of elements
$numbers = range(1, 10);

// Randomize the order of array items
shuffle($numbers);
foreach ($numbers as $value){
    echo "$value" . "<br>";
}
?>

如何在 PHP 中比较两个数组的值

Answer: Use the PHP array\_diff() function

You can use the PHP array\_diff() function to compare an array against one or more other arrays.

The array\_diff() function returns the values in the first array that are not present in any of the other arrays. Let’s try out an example to understand how it actually works:

<?php
$array1 = array("a" => "sky", "star", "moon", "cloud", "moon");
$array2 = array("b" => "sky", "sun", "moon");

// Comparing the values
$result = array_diff($array1, $array2);
print_r($result);
?>

如何在 PHP 中计算数组中数值的总和

Answer: Use the PHP array\_sum() function

You can use the PHP array\_sum() function to calculate the sum of all the numeric values in an array.

Let’s try out the following example to understand how this function basically works:

<?php
$array1 = array(1, 2, 4.5, 8, 15);
$array2 = array("a" => 1.5, "b" => 2.5, "c" => 4.6, "d" => 10.4);

echo array_sum($array1); // Outputs: 30.5
echo "<br>";
echo array_sum($array2); // Outputs: 19
?>

如何在 PHP 中删除数组中的空值

Answer: Use the PHP array\_filter() function

You can simply use the PHP array\_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.

However, if no callback function is specified, all empty entries of array will be removed, such as “” (an empty string), 0 (0 as an integer), 0.0(0 as a float), "0" (0 as a string), NULL, FALSE and array() (an empty array). Let’s try out an example to understand how it actually works:

<?php
$array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false);
var_dump($array);
echo "<br>";

// Filtering the array
$result = array_filter($array);
var_dump($result);
?>

In the above example the values 0 and "0" are also removed from the array. If you want to keep them, you can define a callback function as shown in the following example:

<?php
$array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false);
var_dump($array);
echo "<br>";

// Defining a callback function
function myFilter($var){
    return ($var !== NULL && $var !== FALSE && $var !== "");
}

// Filtering the array
$result = array_filter($array, "myFilter");
var_dump($result);
?>

The callback function myFilter() is called for each element of the array. If myFilter() returns TRUE, then that element will be appended to the result array, otherwise not.

如何在 PHP 中用数组值填充下拉列表

Answer: Use the PHP foreach loop

You can simply use the PHP foreach loop to create or populate HTML