php-doc-en/language/types.xml
Kenneth Schwartz 3ee3100436 changed links to new id's
git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@154496 c90b9560-bf6c-de11-be94-00142212c4b1
2004-03-24 16:39:43 +00:00

2580 lines
76 KiB
XML

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.136 $ -->
<chapter id="language.types">
<title>Types</title>
<sect1 id="language.types.intro">
<title>Introduction</title>
<simpara>
PHP supports eight primitive types.
</simpara>
<para>
Four scalar types:
<itemizedlist>
<listitem>
<simpara>
<type>boolean</type>
</simpara>
</listitem>
<listitem>
<simpara>
<type>integer</type>
</simpara>
</listitem>
<listitem>
<simpara>
<type>float</type> (floating-point number, aka '<type>double</type>')
</simpara>
</listitem>
<listitem>
<simpara>
<type>string</type>
</simpara>
</listitem>
</itemizedlist>
Two compound types:
<itemizedlist>
<listitem>
<simpara>
<type>array</type>
</simpara>
</listitem>
<listitem>
<simpara>
<type>object</type>
</simpara>
</listitem>
</itemizedlist>
And finally two special types:
<itemizedlist>
<listitem>
<simpara>
<type>resource</type>
</simpara>
</listitem>
<listitem>
<simpara>
<type>NULL</type>
</simpara>
</listitem>
</itemizedlist>
This manual also introduces some
<link linkend="language.pseudo-types">pseudo-types</link>
for readability reasons:
<itemizedlist>
<listitem>
<simpara>
<link linkend="language.types.mixed">mixed</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.number">number</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.mixed">callback</link>
</simpara>
</listitem>
</itemizedlist>
You may also find some references to the type "double". Consider
double the same as float, the two names exist only for historic
reasons.
</para>
<simpara>
The type of a variable is usually not set by the programmer;
rather, it is decided at runtime by PHP depending on the context in
which that variable is used.
</simpara>
<note>
<simpara>
If you want to check out the type and value of a certain <link
linkend="language.expressions">expression</link>, use
<function>var_dump</function>.
</simpara>
<para>
If you simply want a human-readable representation of the type for
debugging, use <function>gettype</function>. To check for a certain type,
do <emphasis>not</emphasis> use <function>gettype</function>, but use the
<literal>is_<replaceable>type</replaceable></literal> functions. Some
examples:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$bool = TRUE; // a boolean
$str = "foo"; // a string
$int = 12; // an integer
echo gettype($bool); // prints out "boolean"
echo gettype($str); // prints out "string"
// If this is an integer, increment it by four
if (is_int($int)) {
$int += 4;
}
// If $bool is a string, print it out
// (does not print out anything)
if (is_string($bool)) {
echo "String: $bool";
}
?>
]]>
</programlisting>
</informalexample>
</para>
</note>
<simpara>
If you would like to force a variable to be converted to a certain
type, you may either <link
linkend="language.types.typecasting">cast</link> the variable or
use the <function>settype</function> function on it.
</simpara>
<simpara>
Note that a variable may be evaluated with different values in certain
situations, depending on what type it is at the time. For more
information, see the section on <link
linkend="language.types.type-juggling">Type Juggling</link>. Also, you
may be interested in viewing
<link linkend="types.comparisons">the type comparison tables</link>,
as they show examples of various type related comparisons.
</simpara>
</sect1>
<sect1 id="language.types.boolean">
<title>Booleans</title>
<simpara>
This is the easiest type. A <type>boolean</type> expresses a
truth value. It can be either &true; or &false;.
</simpara>
<note>
<simpara>
The boolean type was introduced in PHP 4.
</simpara>
</note>
<sect2 id="language.types.boolean.syntax">
<title>Syntax</title>
<para>
To specify a boolean literal, use either the keyword &true;
or &false;. Both are case-insensitive.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = True; // assign the value TRUE to $foo
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Usually you
use some kind of <link linkend="language.operators">operator</link>
which returns a <type>boolean</type> value, and then pass it
on to a <link linkend="language.control-structures">control
structure</link>.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
echo "The version is 1.23";
}
// this is not necessary...
if ($show_separators == TRUE) {
echo "<hr>\n";
}
// ...because you can simply type
if ($show_separators) {
echo "<hr>\n";
}
?>
]]>
</programlisting>
</informalexample>
</para>
</sect2>
<sect2 id="language.types.boolean.casting">
<title>Converting to boolean</title>
<simpara>
To explicitly convert a value to <type>boolean</type>, use either
the <literal>(bool)</literal> or the <literal>(boolean)</literal> cast.
However, in most cases you do not need to use the cast, since a value
will be automatically converted if an operator, function or
control structure requires a <type>boolean</type> argument.
</simpara>
<simpara>
See also <link linkend="language.types.type-juggling">Type Juggling</link>.
</simpara>
<para>
When converting to <type>boolean</type>, the following values
are considered &false;:
<itemizedlist>
<listitem>
<simpara>the <link linkend="language.types.boolean">boolean</link>
&false; itself</simpara>
</listitem>
<listitem>
<simpara>the <link linkend="language.types.integer">integer</link
> 0 (zero) </simpara>
</listitem>
<listitem>
<simpara>the <link linkend="language.types.float">float</link>
0.0 (zero) </simpara>
</listitem>
<listitem>
<simpara>the empty <link linkend="language.types.string"
>string</link>, and the <link linkend="language.types.string"
>string</link>
"0"</simpara>
</listitem>
<listitem>
<simpara>an <link linkend="language.types.array">array</link>
with zero elements</simpara>
</listitem>
<listitem>
<simpara>an <link linkend="language.types.object">object</link>
with zero member variables</simpara>
</listitem>
<listitem>
<simpara>the special type <link linkend="language.types.null"
>NULL</link> (including unset variables)
</simpara>
</listitem>
</itemizedlist>
Every other value is considered &true; (including any
<link linkend="language.types.resource">resource</link>).
<warning>
<simpara>
<literal>-1</literal> is considered
&true;, like any other non-zero (whether negative
or positive) number!
</simpara>
</warning>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo gettype((bool) ""); // bool(false)
echo gettype((bool) 1); // bool(true)
echo gettype((bool) -2); // bool(true)
echo gettype((bool) "foo"); // bool(true)
echo gettype((bool) 2.3e5); // bool(true)
echo gettype((bool) array(12)); // bool(true)
echo gettype((bool) array()); // bool(false)
?>
]]>
</programlisting>
</informalexample>
</para>
</sect2>
</sect1>
<sect1 id="language.types.integer">
<title>Integers</title>
<simpara>
An <type>integer</type> is a number of the set
Z = {..., -2, -1, 0, 1, 2, ...}.
</simpara>
<para>
See also:
<link linkend="ref.gmp">Arbitrary length integer / GMP</link>,
<link linkend="language.types.float">Floating point numbers</link>, and
<link linkend="ref.bc">Arbitrary precision / BCMath</link>
</para>
<sect2 id="language.types.integer.syntax">
<title>Syntax</title>
<simpara>
Integers can be specified in decimal (10-based), hexadecimal (16-based)
or octal (8-based) notation, optionally preceded by a sign (- or +).
</simpara>
<para>
If you use the octal notation, you must precede the number with a
<literal>0</literal> (zero), to use hexadecimal notation precede
the number with <literal>0x</literal>.
<example>
<title>Integer literals</title>
<programlisting role="php">
<![CDATA[
<?php
$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)
?>
]]>
</programlisting>
</example>
Formally the possible structure for integer literals is:
<informalexample>
<programlisting>
<![CDATA[
decimal : [1-9][0-9]*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
]]>
</programlisting>
</informalexample>
The size of an integer is platform-dependent, although a
maximum value of about two billion is the usual value
(that's 32 bits signed). PHP does not support unsigned
integers.
</para>
</sect2>
<sect2 id="language.types.integer.overflow">
<title>Integer overflow</title>
<para>
If you specify a number beyond the bounds of the <type>integer</type>
type, it will be interpreted as a <type>float</type> instead. Also, if
you perform an operation that results in a number beyond the bounds of
the <type>integer</type> type, a <type>float</type> will be returned
instead.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$large_number = 2147483647;
var_dump($large_number);
// output: int(2147483647)
$large_number = 2147483648;
var_dump($large_number);
// output: float(2147483648)
// this goes also for hexadecimal specified integers:
var_dump( 0x80000000 );
// output: float(2147483648)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number);
// output: float(50000000000)
?>
]]>
</programlisting>
</informalexample>
<warning>
<simpara>
Unfortunately, there was a bug in PHP so that this
does not always work correctly when there are negative numbers
involved. For example: when you do <literal>-50000 *
$million</literal>, the result will be
<literal>-429496728</literal>. However, when both operands are
positive there is no problem.
</simpara>
<simpara>
This is solved in PHP 4.1.0.
</simpara>
</warning>
</para>
<para>
There is no integer division operator in PHP.
<literal>1/2</literal> yields the <type>float</type>
<literal>0.5</literal>. You can cast the value to
an integer to always round it downwards, or you can
use the <function>round</function> function.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
]]>
</programlisting>
</informalexample>
</para>
</sect2>
<sect2 id="language.types.integer.casting">
<title>Converting to integer</title>
<simpara>
To explicitly convert a value to <type>integer</type>, use either
the <literal>(int)</literal> or the <literal>(integer)</literal> cast.
However, in most cases you do not need to use the cast, since a value
will be automatically converted if an operator, function or
control structure requires an <type>integer</type> argument.
You can also convert a value to integer with the function
<function>intval</function>.
</simpara>
<simpara>
See also <link linkend="language.types.type-juggling">type-juggling</link>.
</simpara>
<sect3 id="language.types.integer.casting.from-boolean">
<title>From <link linkend="language.types.boolean"
>booleans</link></title>
<simpara>
&false; will yield
<literal>0</literal> (zero), and &true;
will yield <literal>1</literal> (one).
</simpara>
</sect3>
<sect3 id="language.types.integer.casting.from-float">
<title>From <link linkend="language.types.float">floating point numbers</link></title>
<simpara>
When converting from float to integer, the number will
be rounded <emphasis>towards zero</emphasis>.
</simpara>
<para>
If the float is beyond the boundaries of integer
(usually <literal>+/- 2.15e+9 = 2^31</literal>),
the result is undefined, since the float hasn't
got enough precision to give an exact integer result.
No warning, not even a notice will be issued in this
case!
</para>
<warning><para>
Never cast an unknown fraction to <type>integer</type>, as this can
sometimes lead to unexpected results.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>
]]>
</programlisting>
</informalexample>
See for more information the <link
linkend="warn.float-precision">warning
about float-precision</link>.
</para></warning>
</sect3>
<sect3 id="language.types.integer.casting.from-string">
<title>From strings</title>
<simpara>
See <link linkend="language.types.string.conversion">String
conversion to numbers</link>
</simpara>
</sect3>
<sect3 id="language.types.integer.casting.from-other">
<title>From other types</title>
<para>
<caution>
<simpara>
Behaviour of converting to integer is undefined for other
types. Currently, the behaviour is the same as if the value
was first <link linkend="language.types.boolean.casting"
>converted to boolean</link>. However, do
<emphasis>not</emphasis> rely on this behaviour, as it can
change without notice.
</simpara>
</caution>
</para>
</sect3>
</sect2>
</sect1>
<sect1 id="language.types.float">
<title>Floating point numbers</title>
<para>
Floating point numbers (AKA "floats", "doubles" or "real numbers") can be
specified using any of the following syntaxes:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
]]>
</programlisting>
</informalexample>
Formally:
<informalexample>
<programlisting role="php">
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})
</programlisting>
</informalexample>
The size of a float is platform-dependent,
although a maximum of ~1.8e308 with a precision of roughly 14
decimal digits is a common value (that's 64 bit IEEE format).
</para>
<warning id="warn.float-precision">
<title>Floating point precision</title>
<para>
It is quite usual that simple decimal fractions like
<literal>0.1</literal> or <literal>0.7</literal> cannot be
converted into their internal binary counterparts without a
little loss of precision. This can lead to confusing results: for
example, <literal>floor((0.1+0.7)*10)</literal> will usually
return <literal>7</literal> instead of the expected
<literal>8</literal> as the result of the internal representation
really being something like <literal>7.9999999999...</literal>.
</para>
<para>
This is related to the fact that it is impossible to exactly
express some fractions in decimal notation with a finite number
of digits. For instance, <literal>1/3</literal> in decimal form
becomes <literal>0.3333333. . .</literal>.
</para>
<para>
So never trust floating number results to the last digit and
never compare floating point numbers for equality. If you really
need higher precision, you should use the <link
linkend="ref.bc">arbitrary precision math functions</link>
or <link linkend="ref.gmp">gmp</link> functions instead.
</para>
</warning>
<sect2 id="language.types.float.casting">
<title>Converting to float</title>
<para>
For information on when and how strings are converted to floats,
see the section titled <link linkend="language.types.string.conversion">String
conversion to numbers</link>. For values of other types, the conversion
is the same as if the value would have been converted to integer
and then to float. See the <link linkend="language.types.integer.casting">Converting
to integer</link> section for more information.
</para>
</sect2>
</sect1>
<sect1 id="language.types.string">
<title>Strings</title>
<para>
A <type>string</type> is series of characters. In PHP,
a character is the same as a byte, that is, there are exactly
256 different characters possible. This also implies that PHP
has no native support of Unicode. See <function>utf8_encode</function>
and <function>utf8_decode</function> for some Unicode support.
</para>
<note>
<simpara>
It is no problem for a string to become very large.
There is no practical bound to the size
of strings imposed by PHP, so there is no reason at all
to worry about long strings.
</simpara>
</note>
<sect2 id="language.types.string.syntax">
<title>Syntax</title>
<para>
A string literal can be specified in three different
ways.
<itemizedlist>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.single">single quoted</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.double">double quoted</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.heredoc">heredoc syntax</link>
</simpara>
</listitem>
</itemizedlist>
</para>
<sect3 id="language.types.string.syntax.single">
<title>Single quoted</title>
<para>
The easiest way to specify a simple string is to
enclose it in single quotes (the character <literal>'</literal>).
</para>
<para>
To specify a literal single
quote, you will need to escape it with a backslash
(<literal>\</literal>), like in many other languages.
If a backslash needs to occur before a single quote or at
the end of the string, you need to double it.
Note that if you try to escape any
other character, the backslash will also be printed! So
usually there is no need to escape the backslash itself.
<note>
<simpara>
In PHP 3, a warning will
be issued at the <literal>E_NOTICE</literal> level when this
happens.
</simpara>
</note>
<note>
<simpara>
Unlike the two other syntaxes, <link
linkend="language.variables">variables</link> and escape sequences
for special characters will <emphasis>not</emphasis> be expanded
when they occur in single quoted strings.
</simpara>
</note>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
]]>
</programlisting>
</informalexample>
</para>
</sect3>
<sect3 id="language.types.string.syntax.double">
<title>Double quoted</title>
<para>
If the string is enclosed in double-quotes ("),
PHP understands more escape sequences for special
characters:
</para>
<table>
<title>Escaped characters</title>
<tgroup cols="2">
<thead>
<row>
<entry>sequence</entry>
<entry>meaning</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>\n</literal></entry>
<entry>linefeed (LF or 0x0A (10) in ASCII)</entry>
</row>
<row>
<entry><literal>\r</literal></entry>
<entry>carriage return (CR or 0x0D (13) in ASCII)</entry>
</row>
<row>
<entry><literal>\t</literal></entry>
<entry>horizontal tab (HT or 0x09 (9) in ASCII)</entry>
</row>
<row>
<entry><literal>\\</literal></entry>
<entry>backslash</entry>
</row>
<row>
<entry><literal>\$</literal></entry>
<entry>dollar sign</entry>
</row>
<row>
<entry><literal>\"</literal></entry>
<entry>double-quote</entry>
</row>
<row>
<entry><literal>\[0-7]{1,3}</literal></entry>
<entry>
the sequence of characters matching the regular
expression is a character in octal notation
</entry>
</row>
<row>
<entry><literal>\x[0-9A-Fa-f]{1,2}</literal></entry>
<entry>
the sequence of characters matching the regular
expression is a character in hexadecimal notation
</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Again, if you try to escape any other character, the
backslash will be printed too!
</para>
<para>
But the most important feature of double-quoted strings
is the fact that variable names will be expanded.
See <link linkend="language.types.string.parsing">string
parsing</link> for details.
</para>
</sect3>
<sect3 id="language.types.string.syntax.heredoc">
<title>Heredoc</title>
<simpara>
Another way to delimit strings is by using heredoc syntax
("&lt;&lt;&lt;"). One should provide an identifier after
<literal>&lt;&lt;&lt;</literal>, then the string, and then the
same identifier to close the quotation.
</simpara>
<simpara>
The closing identifier <emphasis>must</emphasis> begin in the
first column of the line. Also, the identifier used must follow
the same naming rules as any other label in PHP: it must contain
only alphanumeric characters and underscores, and must start with
a non-digit character or underscore.
</simpara>
<warning>
<simpara>
It is very important to note that the line with the closing
identifier contains no other characters, except
<emphasis>possibly</emphasis> a semicolon (<literal>;</literal>).
That means especially that the identifier
<emphasis>may not be indented</emphasis>, and there
may not be any spaces or tabs after or before the semicolon.
It's also important to realize that the first character before
the closing identifier must be a newline as defined by your
operating system. This is <literal>\r</literal> on Macintosh
for example.
</simpara>
<simpara>
If this rule is broken and the closing identifier is not "clean"
then it's not considered to be a closing identifier and PHP
will continue looking for one. If in this case a proper closing
identifier is not found then a parse error will result with the
line number being at the end of the script.
</simpara>
</warning>
<para>
Heredoc text behaves just like a double-quoted string, without
the double-quotes. This means that you do not need to escape quotes
in your here docs, but you can still use the escape codes listed
above. Variables are expanded, but the same care must be taken
when expressing complex variables inside a here doc as with
strings.
<example>
<title>Heredoc string quoting example</title>
<programlisting role="php">
<![CDATA[
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Heredoc support was added in PHP 4.
</para>
</note>
</sect3>
<sect3 id="language.types.string.parsing">
<title>Variable parsing</title>
<simpara>
When a string is specified in double quotes or with
heredoc, <link linkend="language.variables">variables</link> are
parsed within it.
</simpara>
<simpara>
There are two types of syntax: a
<link linkend="language.types.string.parsing.simple">simple</link>
one and a
<link linkend="language.types.string.parsing.complex">complex</link>
one.
The simple syntax is the most common and convenient. It provides a way
to parse a variable, an <type>array</type> value, or an <type>
object</type> property.
</simpara>
<simpara>
The complex syntax was introduced in PHP 4, and can be recognised
by the curly braces surrounding the expression.
</simpara>
<sect4 id="language.types.string.parsing.simple">
<title>Simple syntax</title>
<simpara>
If a dollar sign (<literal>$</literal>) is encountered, the
parser will greedily take as many tokens as possible to form a
valid variable name. Enclose the variable name in curly
braces if you want to explicitly specify the end of the name.
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers"; // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
]]>
</programlisting>
</informalexample>
<simpara>
Similarly, you can also have an <type>array</type> index or an <type>
object</type> property parsed. With array indices, the closing square
bracket (<literal>]</literal>) marks the end of the index. For
object properties the same rules apply as to simple variables,
though with object properties there doesn't exist a trick like
the one with variables.
<!-- XXX isn't &true; :(, this would be the trick
Also, the same trick with curly-braces works if you
want to limit the greediness of parsers.
-->
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.
// Let's show all errors
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";
// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";
// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";
// Works
echo "A banana is " . $fruits['banana'] . ".";
// Works
echo "This square is $square->width meters broad.";
// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>
]]>
<!-- XXX this won't work:
echo "This square is $square->{width}00 centimeters broad.";
// XXX: php developers: it would be consequent to make this work.
// XXX: like the $obj->{expr} syntax outside a string works,
// XXX: analogously to the ${expr} syntax for variable var's.
-->
</programlisting>
</informalexample>
<simpara>
For anything more complex, you should use the complex syntax.
</simpara>
</sect4>
<sect4 id="language.types.string.parsing.complex">
<title>Complex (curly) syntax</title>
<simpara>
This isn't called complex because the syntax is complex,
but because you can include complex expressions this way.
</simpara>
<simpara>
In fact, you can include any value that is in the namespace
in strings with this syntax. You simply write the expression
the same way as you would outside the string, and then include
it in { and }. Since you can't escape '{', this syntax will
only be recognised when the $ is immediately following the {.
(Use "{\$" or "\{$" to get a literal "{$").
Some examples to make it clear:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Let's show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong
// outside a string. In other words, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "You can even write {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
?>
]]>
<!-- maybe it's better to leave this out??
// this works, but i disencourage its use, since this is NOT
// involving functions, rather than mere variables, arrays and objects.
$beer = 'Heineken';
echo "I'd like to have another {${ strrev('reeb') }}, hips";
-->
</programlisting>
</informalexample>
</sect4>
</sect3>
<sect3 id="language.types.string.substr">
<title>String access and modification by character</title>
<para>
Characters within strings may be accessed and modified by specifying the
zero-based offset of the desired character after the string
in curly braces.
</para>
<note>
<simpara>
For backwards compatibility, you can still use array-brackets
for the same purpose. However, this syntax is deprecated as
of PHP 4.
</simpara>
</note>
<para>
<example>
<title>Some string examples</title>
<programlisting role="php">
<![CDATA[
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str{0};
// Get the third character of a string
$third = $str{2};
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str{strlen($str)-1};
// Modify the last character of a string
$str = 'Look at the sea';
$str{strlen($str)-1} = 'e';
?>
]]>
</programlisting>
</example>
</para>
</sect3>
</sect2><!-- end syntax -->
<sect2 id="language.types.string.useful-funcs">
<title>Useful functions and operators</title>
<para>
Strings may be concatenated using the '.' (dot) operator. Note
that the '+' (addition) operator will not work for this. Please
see <link linkend="language.operators.string">String
operators</link> for more information.
</para>
<para>
There are a lot of useful functions for string modification.
</para>
<simpara>
See the <link linkend="ref.strings">string functions section</link>
for general functions, the regular expression functions for
advanced find&amp;replacing (in two tastes:
<link linkend="ref.pcre">Perl</link> and
<link linkend="ref.regex">POSIX extended</link>).
</simpara>
<simpara>
There are also <link linkend="ref.url">functions for URL-strings</link>,
and functions to encrypt/decrypt strings
(<link linkend="ref.mcrypt">mcrypt</link> and
<link linkend="ref.mhash">mhash</link>).
</simpara>
<simpara>
Finally, if you still didn't find what you're looking for,
see also the <link linkend="ref.ctype">character type functions</link>.
</simpara>
</sect2>
<sect2 id="language.types.string.casting">
<title>Converting to string</title>
<para>
You can convert a value to a string using the <literal>(string)</literal>
cast, or the <function>strval</function> function. String conversion
is automatically done in the scope of an expression for you where a
string is needed. This happens when you use the <function>echo</function>
or <function>print</function> functions, or when you compare a variable
value to a string. Reading the manual sections on <link
linkend="language.types">Types</link> and <link
linkend="language.types.type-juggling">Type Juggling</link> will make
the following clearer. See also <function>settype</function>.
</para>
<para>
A <type>boolean</type> &true; value is converted to the string <literal>"1"</literal>,
the &false; value is represented as <literal>""</literal> (empty string).
This way you can convert back and forth between boolean and string values.
</para>
<para>
An <type>integer</type> or a floating point number (<type>float</type>)
is converted to a string representing the number with its digits
(including the exponent part for floating point numbers).
</para>
<para>
Arrays are always converted to the string <literal>"Array"</literal>,
so you cannot dump out the contents of an <type>array</type> with
<function>echo</function> or <function>print</function> to see what is inside
them. To view one element, you'd do something like <literal>
echo $arr['foo']</literal>. See below for tips on dumping/viewing the
entire contents.
</para>
<para>
Objects are always converted to the string <literal>"Object"</literal>.
If you would like to print out the member variable values of an
<type>object</type> for debugging reasons, read the paragraphs
below. If you would like to find out the class name of which an object
is an instance of, use <function>get_class</function>.
</para>
<para>
Resources are always converted to strings with the structure
<literal>"Resource id #1"</literal> where <literal>1</literal> is
the unique number of the <type>resource</type> assigned by PHP during runtime.
If you would like to get the type of the resource, use
<function>get_resource_type</function>.
</para>
<para>
&null; is always converted to an empty string.
</para>
<para>
As you can see above, printing out the arrays, objects or resources does not
provide you any useful information about the values themselfs. Look at the
functions <function>print_r</function> and <function>var_dump</function>
for better ways to print out values for debugging.
</para>
<para>
You can also convert PHP values to strings to store them permanently. This
method is called serialization, and can be done with the function
<function>serialize</function>. You can also serialize PHP values to
XML structures, if you have <link linkend="ref.wddx">WDDX</link> support
in your PHP setup.
</para>
</sect2>
<sect2 id="language.types.string.conversion">
<title>String conversion to numbers</title>
<simpara>
When a string is evaluated as a numeric value, the resulting
value and type are determined as follows.
</simpara>
<simpara>
The string will evaluate as a <type>float</type> if it contains any of the
characters '.', 'e', or 'E'. Otherwise, it will evaluate as an
integer.
</simpara>
<para>
The value is given by the initial portion of the string. If the
string starts with valid numeric data, this will be the value
used. Otherwise, the value will be 0 (zero). Valid numeric data
is an optional sign, followed by one or more digits (optionally
containing a decimal point), followed by an optional
exponent. The exponent is an 'e' or 'E' followed by one or more
digits.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>
]]>
</programlisting>
</informalexample>
<simpara>
For more information on this conversion, see the Unix manual page
for strtod(3).
</simpara>
<para>
If you would like to test any of the examples in this section,
you can cut and paste the examples and insert the following line
to see for yourself what's going on:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Do not expect to get the code of one character by converting it
to integer (as you would do in C for example). Use the functions
<function>ord</function> and <function>chr</function> to convert
between charcodes and characters.
</para>
</sect2>
</sect1><!-- end string -->
<sect1 id="language.types.array">
<title>Arrays</title>
<para>
An array in PHP is actually an ordered map. A map is a type that
maps <emphasis>values</emphasis> to <emphasis>keys</emphasis>.
This type is optimized in several ways,
so you can use it as a real array, or a list (vector),
hashtable (which is an implementation of a map),
dictionary, collection,
stack, queue and probably more. Because you can have another
PHP array as a value, you can also quite easily simulate
trees.
</para>
<para>
Explanation of those data structures is beyond the scope of this
manual, but you'll find at least one example for each of them.
For more information we refer you to external literature about
this broad topic.
</para>
<sect2 id="language.types.array.syntax">
<title>Syntax</title>
<sect3 id="language.types.array.syntax.array-func">
<title>Specifying with <function>array</function></title>
<para>
An <type>array</type> can be created by the <function>array</function>
language-construct. It takes a certain number of comma-separated
<literal><replaceable>key</replaceable> =&gt; <replaceable
>value</replaceable></literal>
pairs.
</para>
<para>
<synopsis>
array( <optional> <replaceable>key</replaceable> =&gt; </optional> <replaceable>value</replaceable>
, ...
)
// <replaceable>key</replaceable> may be an <type>integer</type> or <type>string</type>
// <replaceable>value</replaceable> may be any value
</synopsis>
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
A <varname>key</varname> may be either an
<literal>integer</literal> or a <type>string</type>. If a key is
the standard representation of an <type>integer</type>, it will
be interpreted as such (i.e. <literal>"8"</literal> will be
interpreted as <literal>8</literal>, while
<literal>"08"</literal> will be interpreted as
<literal>"08"</literal>). There are no different indexed and
associative array types in PHP; there is only one array type,
which can both contain integer and string indices.
</para>
<para>
A value can be of any PHP type.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
If you do not specify a key for a given value, then the maximum
of the integer indices is taken, and the new key will be that
maximum value + 1. If you specify a key that already has a value
assigned to it, that value will be overwritten.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
]]>
</programlisting>
</informalexample>
</para>
<warning>
<simpara>
As of PHP 4.3.0, the index generation behaviour described
above has changed. Now, if you append to an array in which
the current maximum key is negative, then the next key
created will be zero (<literal>0</literal>). Before, the new
index would have been set to the largest existing key + 1,
the same as positive indices are.
</simpara>
</warning>
<para>
Using &true; as a key will evaluate to <type>integer</type>
<literal>1</literal> as key. Using &false; as a key will evaluate
to <type>integer</type> <literal>0</literal> as key. Using
<literal>NULL</literal> as a key will evaluate to the empty
string. Using the empty string as key will create (or overwrite)
a key with the empty string and its value; it is not the same as
using empty brackets.
</para>
<para>
You cannot use arrays or objects as keys. Doing so will result in a
warning: <literal>Illegal offset type</literal>.
</para>
</sect3>
<sect3 id="language.types.array.syntax.modifying">
<title>Creating/modifying with square-bracket syntax</title>
<para>
You can also modify an existing array by explicitly setting
values in it.
</para>
<para>
This is done by assigning values to the array while specifying the
key in brackets. You can also omit the key, add an empty pair
of brackets ("<literal>[]</literal>") to the variable name in that case.
<synopsis>
$arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>;
$arr[] = <replaceable>value</replaceable>;
// <replaceable>key</replaceable> may be an <type>integer</type> or <type>string</type>
// <replaceable>value</replaceable> may be any value
</synopsis>
If <varname>$arr</varname> doesn't exist yet, it will be created.
So this is also an alternative way to specify an array.
To change a certain value, just assign a new value
to an element specified with its key. If you want to
remove a key/value pair, you need to <function>unset</function> it.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
]]>
</programlisting>
</informalexample>
</para>
<note>
<para>
As mentioned above, if you provide the brackets with no key
specified, then the maximum of the existing integer indices is
taken, and the new key will be that maximum value + 1 . If no
integer indices exist yet, the key will be <literal>0</literal>
(zero). If you specify a key that already has a value assigned
to it, that value will be overwritten.
</para>
<para>
<warning>
<simpara>
As of PHP 4.3.0, the index generation behaviour described
above has changed. Now, if you append to an array in which
the current maximum key is negative, then the next key
created will be zero (<literal>0</literal>). Before, the new
index would have been set to the largest existing key + 1,
the same as positive indices are.
</simpara>
</warning>
</para>
<para>
Note that the maximum integer key used for this <emphasis>need
not currently exist in the array</emphasis>. It simply must
have existed in the array at some time since the last time the
array was re-indexed. The following example illustrates:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0 as you
// might expect).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
]]>
</programlisting>
<para>
The above example would produce the following output:
<screen>
<![CDATA[
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
]]>
</screen>
</para>
</informalexample>
</note>
</sect3>
</sect2><!-- end syntax -->
<sect2 id="language.types.array.useful-funcs">
<title>Useful functions</title>
<para>
There are quite a few useful functions for working with arrays.
See the <link linkend="ref.array">array functions</link> section.
</para>
<note>
<para>
The <function>unset</function> function allows unsetting keys of an
array. Be aware that the array will NOT be reindexed. If you only
use "usual integer indices" (starting from zero, increasing by one),
you can achieve the reindex effect by using <function>array_values</function>.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>
]]>
</programlisting>
</informalexample>
</para>
</note>
<para>
The <link linkend="control-structures.foreach">foreach</link>
control structure exists specifically for arrays. It
provides an easy way to traverse an array.
</para>
</sect2>
<sect2 id="language.types.array.donts">
<title>Array do's and don'ts</title>
<sect3 id="language.types.array.foo-bar">
<title>Why is <literal>$foo[bar]</literal> wrong?</title>
<para>
You should always use quotes around a string literal
array index. For example, use $foo['bar'] and not
$foo[bar]. But why is $foo[bar] wrong? You might have seen the
following syntax in old scripts:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
]]>
</programlisting>
</informalexample>
This is wrong, but it works. Then, why is it wrong? The reason
is that this code has an undefined constant (bar) rather than a
string ('bar' - notice the quotes), and PHP may in future define
constants which, unfortunately for your code, have the same
name. It works because PHP automatically converts a
<emphasis>bare string</emphasis> (an unquoted string which does
not correspond to any known symbol) into a string which contains
the bare string. For instance, if there is no defined constant
named <constant>bar</constant>, then PHP will substitute in the
string <literal>'bar'</literal> and use that.
</para>
<note>
<simpara>
This does not mean to <emphasis>always</emphasis> quote the
key. You do not want to quote keys which are <link
linkend="language.constants">constants</link> or <link
linkend="language.variables">variables</link>, as this will
prevent PHP from interpreting them.
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>
]]>
</programlisting>
</informalexample>
<para>
The output from the above is:
<screen>
<![CDATA[
Checking 0:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 1
Checking 1:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 2
]]>
</screen>
</para>
</note>
<para>
More examples to demonstrate this fact:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Let's show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// Let's define a constant to demonstrate what's going on. We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay as it's inside a string. Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple
// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
When you turn <function>error_reporting</function> up to show
<constant>E_NOTICE</constant> level errors (such as setting
it to <constant>E_ALL</constant>) then you will see these
errors. By default, <link linkend="ini.error-reporting">
error_reporting</link> is turned down to not show them.
</para>
<para>
As stated in the <link
linkend="language.types.array.syntax">syntax</link> section,
there must be an expression between the square brackets
('<literal>[</literal>' and '<literal>]</literal>'). That means
that you can write things like this:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo $arr[somefunc($bar)];
?>
]]>
</programlisting>
</informalexample>
This is an example of using a function return value
as the array index. PHP also knows about constants,
as you may have seen the <literal>E_*</literal> ones
before.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>
]]>
</programlisting>
</informalexample>
Note that <literal>E_ERROR</literal> is also a valid identifier,
just like <literal>bar</literal> in the first example. But the last
example is in fact the same as writing:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>
]]>
</programlisting>
</informalexample>
because <literal>E_ERROR</literal> equals <literal>1</literal>, etc.
</para>
<para>
As we already explained in the above examples,
<literal>$foo[bar]</literal> still works but is wrong.
It works, because <literal>bar</literal> is due to its syntax
expected to be a constant expression. However, in this case no
constant with the name <literal>bar</literal> exists. PHP now
assumes that you meant <literal>bar</literal> literally,
as the string <literal>"bar"</literal>, but that you forgot
to write the quotes.
</para>
<sect4>
<title>So why is it bad then?</title>
<para>
At some point in the future, the PHP team might want to add another
constant or keyword, or you may introduce another constant into your
application, and then you get in trouble. For example,
you already cannot use the words <literal>empty</literal> and
<literal>default</literal> this way, since they are special
<link linkend="reserved">reserved keywords</link>.
</para>
<note>
<simpara>
To reiterate, inside a double-quoted <type>string</type>, it's
valid to not surround array indexes with quotes so
<literal>"$foo[bar]"</literal> is valid. See the above
examples for details on why as well as the section on
<link linkend="language.types.string.parsing">variable parsing
in strings</link>.
</simpara>
</note>
</sect4>
</sect3>
</sect2>
<sect2 id="language.types.array.casting">
<title>Converting to array</title>
<para>
For any of the types: <type>integer</type>, <type>float</type>,
<type>string</type>, <type>boolean</type> and <type>resource</type>,
if you convert a value to an <type>array</type>, you get an array
with one element (with index 0), which is the scalar value you
started with.
</para>
<para>
If you convert an <type>object</type> to an array, you get the
properties (member variables) of that object as the array's elements.
The keys are the member variable names.
</para>
<para>
If you convert a &null; value to an array, you get an empty array.
</para>
</sect2>
<sect2 id="language.types.array.comparing">
<title>Comparing</title>
<para>
It is possible to compare arrays by <function>array_diff</function> and
by <link linkend="language.operators.array">Array operators</link>.
</para>
</sect2>
<sect2 id="language.types.array.examples">
<title>Examples</title>
<para>
The array type in PHP is very versatile, so here will be some
examples to show you the full power of arrays.
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// this
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>
]]>
</programlisting>
</informalexample>
</para>
<example>
<title>Using array()</title>
<programlisting role="php">
<![CDATA[
<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// strictly numerical keys
$array = array( 7,
8,
0,
156,
-10
);
// this is the same as array(0 => 7, 1 => 8, ...)
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
?>
]]>
<!-- TODO example of
- overwriting keys
- using vars/functions as key/values
- warning about references
-->
</programlisting>
</example>
<example id="language.types.array.examples.loop">
<title>Collection</title>
<programlisting role="php">
<![CDATA[
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
]]>
</programlisting>
<para>
This will output:
</para>
<screen>
<![CDATA[
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
]]>
</screen>
</example>
<para>
Note that it is currently not possible to change the values of the array
directly in such a loop.
<!--
Should be made possible, if you write:
foreach ( $colors as &$color )
See bug#3074
-->
A workaround is the following:
<example id="language.types.array.examples.changeloop">
<title>Collection</title>
<programlisting role="php">
<![CDATA[
<?php
foreach ($colors as $key => $color) {
// won't work:
//$color = strtoupper($color);
// works:
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
]]>
</programlisting>
<para>
This will output:
</para>
<screen>
<![CDATA[
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
]]>
</screen>
</example>
</para>
<para>
This example creates a one-based array.
<example>
<title>One-based index</title>
<programlisting role="php">
<![CDATA[
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
]]>
</programlisting>
<para>
This will output:
</para>
<screen>
<![CDATA[
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
]]>
</screen>
</example>
</para>
<example>
<title>Filling an array</title>
<programlisting role="php">
<![CDATA[
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
]]>
</programlisting>
</example>
<para>
Arrays are ordered. You can also change the order using various
sorting functions. See the <link linkend="ref.array">array
functions</link> section for more information. You can count
the number of items in an array using the
<function>count</function> function.
</para>
<example>
<title>Sorting an array</title>
<programlisting role="php">
<![CDATA[
<?php
sort($files);
print_r($files);
?>
]]>
</programlisting>
</example>
<para>
Because the value of an array can be anything, it can also be
another array. This way you can make recursive and
multi-dimensional arrays.
</para>
<example>
<title>Recursive and multi-dimensional arrays</title>
<programlisting role="php">
<![CDATA[
<?php
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>
]]>
</programlisting>
</example>
<para>
You should be aware that array assignment always involves
value copying. You need to use the reference operator to copy
an array by reference.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
]]>
</programlisting>
</informalexample>
</para>
</sect2>
</sect1>
<sect1 id="language.types.object">
<title>Objects</title>
<sect2 id="language.types.object.init">
<title>Object Initialization</title>
<para>
To initialize an object, you use the <literal>new</literal>
statement to instantiate the object to a variable.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
]]>
</programlisting>
</informalexample>
</para>
<simpara>
For a full discussion, please read the section <link
linkend="language.oop">Classes and Objects</link>.
</simpara>
</sect2>
<sect2 id="language.types.object.casting">
<title>Converting to object</title>
<para>
If an object is converted to an object, it is not modified. If a value
of any other type is converted to an object, a new instance of the
<literal>stdClass</literal> built in class is created. If the value
was null, the new instance will be empty. For any other value, a
member variable named <literal>scalar</literal> will contain the
value.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>
]]>
</programlisting>
</informalexample>
</para>
</sect2>
</sect1>
<sect1 id="language.types.resource">
<title>Resource</title>
<para>
A resource is a special variable, holding
a reference to an external resource. Resources
are created and used by special functions.
See the <link linkend="resource">appendix</link>
for a listing of all these
functions and the corresponding resource types.
</para>
<note>
<simpara>
The resource type was introduced in PHP 4
</simpara>
</note>
<sect2 id="language.types.resource.casting">
<title>Converting to resource</title>
<para>
As resource types hold special handlers to opened
files, database connections, image canvas areas and
the like, you cannot convert any value to a resource.
</para>
</sect2>
<sect2 id="language.types.resource.self-destruct">
<title>Freeing resources</title>
<para>
Due to the reference-counting system introduced
with PHP 4's Zend Engine, it is automatically detected
when a resource is no longer referred to (just
like Java). When this is
the case, all resources that were in use for this
resource are made free by the garbage collector.
For this reason, it is rarely ever necessary to
free the memory manually by using some free_result
function.
<note>
<simpara>
Persistent database links are special, they
are <emphasis>not</emphasis> destroyed by the
garbage collector. See also the section about <link
linkend="features.persistent-connections">persistent
connections</link>.
</simpara>
</note>
</para>
</sect2>
</sect1>
<sect1 id="language.types.null">
<title>NULL</title>
<para>
The special &null; value represents
that a variable has no value. &null; is the only possible value of type
<type>NULL</type>.
</para>
<note>
<simpara>
The null type was introduced in PHP 4
</simpara>
</note>
<para>
A variable is considered to be &null; if
<itemizedlist>
<listitem>
<para>
it has been assigned the constant &null;.
</para>
</listitem>
<listitem>
<para>
it has not been set to any value yet.
</para>
</listitem>
<listitem>
<para>
it has been <function>unset</function>.
</para>
</listitem>
</itemizedlist>
</para>
<sect2 id="language.types.null.syntax">
<title>Syntax</title>
<para>
There is only one value of type &null;, and that is
the case-insensitive keyword &null;.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$var = NULL;
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
See also <function>is_null</function> and <function>unset</function>.
</para>
</sect2>
</sect1>
<sect1 id="language.pseudo-types">
<title>Pseudo-types used in this documentation</title>
<sect2 id="language.types.mixed">
<title>mixed</title>
<para>
<literal>mixed</literal> indicates that a parameter may accept multiple (but not
necessarily all) types.
</para>
<para>
<function>gettype</function> for example will accept all PHP types,
while <function>str_replace</function> will accept strings and arrays.
</para>
</sect2>
<sect2 id="language.types.number">
<title>number</title>
<para>
<literal>number</literal> indicates that a parameter can be either
<type>integer</type> or <type>float</type>.
</para>
</sect2>
<sect2 id="language.types.callback">
<title>callback</title>
<para>
Some functions like <function>call_user_func</function>
or <function>usort</function> accept user defined
callback functions as a parameter. Callback functions can not only
be simple functions but also object methods including static class
methods.
</para>
<para>
A PHP function is simply passed by its name as a string. You can
pass any builtin or user defined function with the exception of
<function>array</function>,
<function>echo</function>,
<function>empty</function>,
<function>eval</function>,
<function>exit</function>,
<function>isset</function>,
<function>list</function>,
<function>print</function> and
<function>unset</function>.
</para>
<para>
A method of an instantiated object is passed as an array containing
an object as the element with index 0 and a method name as the
element with index 1.
</para>
<para>
Static class methods can also be passed without instantiating an
object of that class by passing the class name instead of an
object as the element with index 0.
</para>
<para>
<example>
<title>
Callback function examples
</title>
<programlisting role="php">
<![CDATA[
<?php
// simple callback example
function my_callback_function() {
echo 'hello world!';
}
call_user_func('my_callback_function');
// method callback examples
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
// static class method call without instantiating an object
call_user_func(array('MyClass', 'myCallbackMethod'));
// object method call
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>
]]>
</programlisting>
</example>
</para>
</sect2>
</sect1>
<sect1 id="language.types.type-juggling">
<title>Type Juggling</title>
<simpara>
PHP does not require (or support) explicit type definition in
variable declaration; a variable's type is determined by the
context in which that variable is used. That is to say, if you
assign a string value to variable <parameter>$var</parameter>,
<parameter>$var</parameter> becomes a string. If you then assign an
integer value to <parameter>$var</parameter>, it becomes an
integer.
</simpara>
<para>
An example of PHP's automatic type conversion is the addition
operator '+'. If any of the operands is a float, then all
operands are evaluated as floats, and the result will be a
float. Otherwise, the operands will be interpreted as integers,
and the result will also be an integer. Note that this does NOT
change the types of the operands themselves; the only change is in
how the operands are evaluated.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = "0"; // $foo is string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)
?>
]]>
<!-- bad example, no real operator (must be used with variable, modifies it too)
$foo++; // $foo is the string "1" (ASCII 49)
TODO: explain ++/- - behaviour with strings
examples:
++'001' = '002'
++'abc' = 'abd'
++'xyz' = 'xza'
++'9.9' = '9.0'
++'-3' = '-4'
- -'9' = 8 (integer!)
- -'5.5' = '5.5'
- -'-9' = -10 (integer)
- -'09' = 8 (integer)
- -'abc' = 'abc'
-->
</programlisting>
</informalexample>
</para>
<simpara>
If the last two examples above seem odd, see <link
linkend="language.types.string.conversion">String
conversion to numbers</link>.
</simpara>
<simpara>
If you wish to force a variable to be evaluated as a certain type,
see the section on <link linkend="language.types.typecasting">Type
casting</link>. If you wish to change the type of a variable, see
<function>settype</function>.
</simpara>
<para>
If you would like to test any of the examples in this section, you
can use the <function>var_dump</function> function.
</para>
<note>
<para>
The behaviour of an automatic conversion to array is currently
undefined.
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = "1"; // $a is a string
$a[0] = "f"; // What about string offsets? What happens?
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Since PHP (for historical reasons) supports indexing into strings
via offsets using the same syntax as array indexing, the example
above leads to a problem: should $a become an array with its first
element being "f", or should "f" become the first character of the
string $a?
</para>
<para>
The current versions of PHP interpret the second assignment as
a string offset identification, so $a becomes "f", the result
of this automatic conversion however should be considered
undefined. PHP 4 introduced the new curly bracket syntax to access
characters in string, use this syntax instead of the one presented
above:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = "abc"; // $a is a string
$a{1} = "f"; // $a is now "afc"
?>
]]>
</programlisting>
</informalexample>
See the section titled <link linkend="language.types.string.substr">String
access by character</link> for more information.
</para>
</note>
<sect2 id="language.types.typecasting">
<title>Type Casting</title>
<para>
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which
is to be cast.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
The casts allowed are:
<itemizedlist>
<listitem>
<simpara>(int), (integer) - cast to integer</simpara>
</listitem>
<listitem>
<simpara>(bool), (boolean) - cast to boolean</simpara>
</listitem>
<listitem>
<simpara>(float), (double), (real) - cast to float</simpara>
</listitem>
<listitem>
<simpara>(string) - cast to string</simpara>
</listitem>
<listitem>
<simpara>(array) - cast to array</simpara>
</listitem>
<listitem>
<simpara>(object) - cast to object</simpara>
</listitem>
</itemizedlist>
</para>
<para>
Note that tabs and spaces are allowed inside the parentheses, so
the following are functionally equivalent:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>
]]>
</programlisting>
</informalexample>
</para>
<note>
<para>
Instead of casting a variable to string, you can also enclose
the variable in double quotes.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = 10; // $foo is an integer
$str = "$foo"; // $str is a string
$fst = (string) $foo; // $fst is also a string
// This prints out that "they are the same"
if ($fst === $str) {
echo "they are the same";
}
?>
]]>
</programlisting>
</informalexample>
</para>
</note>
<para>
It may not be obvious exactly what will happen when casting
between certain types. For more info, see these sections:
<itemizedlist>
<listitem>
<simpara><link linkend="language.types.boolean.casting">Converting to
boolean</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.integer.casting">Converting to
integer</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.float.casting">Converting to
float</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.string.casting">Converting to
string</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.array.casting">Converting to
array</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.object.casting">Converting to
object</link></simpara>
</listitem>
<listitem>
<simpara><link linkend="language.types.resource.casting">Converting to
resource</link></simpara>
</listitem>
<!-- don't exist yet
<listitem>
<simpara><link linkend="language.types.null.casting">Converting to
&null;</link></simpara>
</listitem>
-->
<listitem>
<simpara>
<link linkend="types.comparisons">The type comparison tables</link>
</simpara>
</listitem>
</itemizedlist>
</para>
</sect2>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->