Interpreting Other Types As Booleans

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

PHP

Interpreting other types as Booleans


Here are the rules for determine the "truth" of any value not already of the Boolean type:

 If the value is a number, it is false if exactly equal to zero and true otherwise.

 If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.

 Values of type NULL are always false.

 If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.

 Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).

 Don't use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this:

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed:

$my_var = null;

A variable that has been assigned NULL has the following properties:

 It evaluates to FALSE in a Boolean context.



29
PHP

 It returns FALSE when tested with IsSet() function.

Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string:

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>

This will produce the following result:

My $variable will not print!\n


My name will print

There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:

 Certain character sequences beginning with backslash (\) are replaced with special
characters

 Variable names (starting with $) are replaced with string representations of their
values.

The escape-sequence replacements are:

 \n is replaced by the newline character

30
PHP

 \r is replaced by the carriage-return character

 \t is replaced by the tab character

 \$ is replaced by the dollar sign itself ($)

 \" is replaced by a single double-quote (")

 \\ is replaced by a single backslash (\)

Here Document
You can assign multiple lines to a single string variable using here document:

<?php

$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;

echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;

print $channel;
?>

This will produce the following result:

This uses the "here document" syntax to output

multiple lines with variable interpolation. Note

31
PHP

that the here document terminator must appear on a


line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>

Variable Naming
Rules for naming a variable is:

 Variable names must begin with a letter or underscore character.

 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc

There is no size limit for variables.

PHP – Variables
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:

 Local variables

 Function parameters

 Global variables

 Static variables

PHP Local Variables


A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function:

<?
$x = 4;
function assignx () {
32
PHP

$x = 0;
print "\$x inside function is $x.
";
}
assignx();
print "\$x outside of function is $x.
";
?>

This will produce the following result.

$x inside function is 0.
$x outside of function is 4.

PHP Function Parameters


PHP Functions are covered in detail in PHP Function Chapter. In short, a function is a small
unit of program which can take some input in the form of parameters and does some
processing and may return a value.

Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be:

<?
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}

$retval = multiply (10);


Print "Return value is $retval\n";
?>

This will produce the following result.

Return value is 100

33
PHP

PHP Global Variables


In contrast to local variables, a global variable can be accessed in any part of the program.
However, in order to be modified, a global variable must be explicitly declared to be global in
the function in which it is to be modified. This is accomplished, conveniently enough, by
placing the keyword GLOBAL in front of the variable that should be recognized as global.
Placing this keyword in front of an already existing variable tells PHP to use the variable having
that name. Consider an example:

<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>

This will produce the following result.

Somevar is 16

PHP Static Variables


The final type of variable scoping that I discuss is known as static. In contrast to the variables
declared as function parameters, which are destroyed on the function's exit, a static variable
will not lose its value when the function exits and will still hold that value should the function
be called again.

You can declare a variable to be static simply by placing the keyword STATIC in front of the
variable name.

<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "
";

34
PHP

}
keep_track();
keep_track();
keep_track();
?>

This will produce the following result.

1
2
3

35
PHP ─ CONSTANTS PHP

A constant is a name or an identifier for a simple value. A constant value cannot change
during the execution of the script. By default, a constant is case-sensitive. By convention,
constant identifiers are always uppercase. A constant name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores. If you have defined a constant,
it can never be changed or undefined.

To define a constant you have to use define() function and to retrieve the value of a constant,
you have to simply specifying its name. Unlike with variables, you do not need to have a
constant with a $. You can also use the function constant() to read a constant's value if you
wish to obtain the constant's name dynamically.

constant() function
As indicated by the name, this function will return the value of the constant.

This is useful when you want to retrieve value of a constant, but you do not know its name,
i.e., it is stored in a variable or returned by a function.

constant() example
<?php

define("MINSIZE", 50);

echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line

?>

Only scalar data (boolean, integer, float and string) can be contained in constants.

Differences between constants and variables are


 There is no need to write a dollar sign ($) before a constant, where as in Variable one
has to write a dollar sign.

 Constants cannot be defined by simple assignment, they may only be defined using
the define() function.

 Constants may be defined and accessed anywhere without regard to variable scoping
rules.

36
PHP

 Once the Constants have been set, may not be redefined or undefined.

Valid and invalid constant names


// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing")
// Invalid constant names
define("2TWO", "second thing");
define("__THREE__", "third value");

PHP Magic constants


PHP provides a large number of predefined constants to any script which it runs.

There are five magical constants that change depending on where they are used. For example,
the value of __LINE__ depends on the line that it's used on in your script. These special
constants are case-insensitive and are as follows:

The following table lists a few "magical" PHP constants along with their description:

Name Description

__LINE__ The current line number of the file.

__FILE__ The full path and filename of the file. If used inside an include, the
name of the included file is returned. Since PHP
4.0.2, __FILE__ always contains an absolute path whereas in older
versions it contained relative path under some circumstances.

__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant
returns the function name as it was declared (case-sensitive). In PHP
4 its value is always lowercased.

__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant
returns the class name as it was declared (case-sensitive). In PHP 4
its value is always lowercased.

__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is
returned as it was declared (case-sensitive).

37
PHP ─ OPERATOR TYPES PHP

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here
4 and 5 are called operands and + is called operator. PHP language supports following type
of operators.

 Arithmetic Operators

 Comparison Operators

 Logical (or Relational) Operators

 Assignment Operators

 Conditional (or ternary) Operators

Let’s have a look on all operators one by one.

Arithmetic Operators
The following arithmetic operators are supported by PHP language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide the numerator by denominator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value by A++ will give 11


one

-- Decrement operator, decreases integer value A-- will give 9


by one

38
PHP

Example
Try the following example to understand all the arithmetic operators. Copy and paste following
PHP program in test.php file and keep it in your PHP Server's document root and browse it
using any browser.

<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;

$c = $a + $b;
echo "Addition Operation Result: $c <br/>";
$c = $a - $b;
echo "Subtraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html>

This will produce the following result:

Addition Operation Result: 62


Subtraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1

39

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy