Mastering PHP’s true Boolean: Conditions, Returns, and File Writing
This guide explains PHP’s true boolean value, demonstrates its use in conditional statements, shows how functions like file_put_contents return true on success, and provides practical code examples for assigning and testing true in real‑world scripts.
What true means in PHP
In PHP, true is a boolean keyword representing the logical value 1, while false represents 0. These values are commonly used to control flow in conditional statements and to indicate successful outcomes of functions.
Using true in conditional statements
A simple if check can test a boolean expression directly:
if (true) {
echo '这个条件为真!';
}The code above outputs “这个条件为真!” because the condition evaluates to true.
Functions that return true
Many PHP functions return true when they succeed. For example, file_put_contents() writes a string to a file and returns true on success, false on failure. The following example writes “Hello World!” to test.txt and reports the result:
$content = "Hello World!";
$file = "test.txt";
if (file_put_contents($file, $content)) {
echo "写入成功!";
} else {
echo "写入失败!";
}If the write operation succeeds, the script prints “写入成功!”. Otherwise it prints “写入失败!”.
Assigning true to variables
You can store boolean values in variables and use them in conditions. The example below sets $is_passed to true and checks it:
$is_passed = true;
if ($is_passed) {
echo "你通过了测试!";
} else {
echo "你没有通过测试!";
}Because $is_passed is true, the output is “你通过了测试!”.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
