Expanded string and array information including many example updates, many

more manual links, and a little cleanup.  Added a decent amount of information
on using arrays within strings and further explained $foo[bar].  This also closes bug #20601


git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@113075 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Philip Olson 2003-01-22 23:55:56 +00:00
parent d292a19070
commit 4d831c8b14

View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.105 $ -->
<!-- $Revision: 1.106 $ -->
<chapter id="language.types">
<title>Types</title>
@ -667,16 +667,25 @@ EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})
<![CDATA[
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in strings
this way';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// output: ... "I'll be back"
echo 'Are you sure you want to delete C:\\*.*?';
// output: ... delete C:\*.*?
echo 'Are you sure you want to delete C:\*.*?';
// output: ... delete C:\*.*?
echo 'I am trying to include at this point: \n a newline';
// output: ... this point: \n a newline
// 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>
@ -847,7 +856,8 @@ EOT;
<title>Variable parsing</title>
<simpara>
When a string is specified in double quotes or with
heredoc, variables are parsed within it.
heredoc, <link linkend="language.variables">variables</link> are
parsed within it.
</simpara>
<simpara>
There are two types of syntax, a
@ -856,7 +866,8 @@ EOT;
<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 array value, or an object property.
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
@ -879,14 +890,15 @@ $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 array index or an object
property parsed. With array indices, the closing square bracket
(<literal>]</literal>) marks the end of the index. For
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.
@ -901,11 +913,32 @@ echo "He drank some ${beer}s"; // works
<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');
// note that this works differently outside string-quotes
// 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.
@ -944,18 +977,39 @@ echo "This square is $square->{width}00 centimeters broad.";
<programlisting role="php">
<![CDATA[
<?php
// Let's show all errors
error_reporting(E_ALL);
$great = 'fantastic';
echo "This is { $great}"; // won't work, outputs: This is { fantastic}
echo "This is {$great}"; // works, outputs: This is 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.
// This is wrong for the same reason as $foo[bar] is wrong
// outside a string. In otherwords, 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]}";
echo "You should do it this way: {$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}}";
?>
]]>
@ -994,6 +1048,9 @@ echo "I'd like to have another {${ strrev('reeb') }}, hips";
$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};
@ -1045,36 +1102,41 @@ $last = $str{strlen($str)-1};
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.
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 boolean &true; value is converted to the string <literal>"1"</literal>,
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 integer or a floating point number is converted to a string
representing the number with its digits (includig the exponent part
for floating point numbers).
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 array with <function>echo</function>
or <function>print</function> to see what is inside them. See the information
below for more tips.
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 object
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>.
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 resource assigned by PHP during runtime.
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>
@ -1123,14 +1185,14 @@ $last = $str{strlen($str)-1};
<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 = 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)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>
]]>
</programlisting>
@ -1212,7 +1274,10 @@ array( <optional> <replaceable>key</replaceable> =&gt; </optional> <replaceable
<programlisting role="php">
<![CDATA[
<?php
array("foo" => "bar", 12 => true);
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
]]>
</programlisting>
@ -1234,7 +1299,11 @@ array("foo" => "bar", 12 => true);
<programlisting role="php">
<![CDATA[
<?php
array("somearray" => array(6 => 5, 13 => 9, "a" => 43));
$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>
@ -1244,7 +1313,7 @@ array("somearray" => array(6 => 5, 13 => 9, "a" => 43));
If you omit a key, the maximum of the integer-indices is taken, and
the new key will be that maximum + 1. As integers can be negative,
this is also true for negative indices. Having e.g. the highest index
being <literal>-6</literal> will result in being <literal>-5</literal>
being <literal>-6</literal> will result in <literal>-5</literal> being
the new key. 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.
@ -1390,6 +1459,64 @@ echo $foo[bar];
undefined constant gets converted to a string of the same name
automatically for backward compatibility reasons.
</para>
<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
@ -1399,7 +1526,7 @@ echo $foo[bar];
<programlisting role="php">
<![CDATA[
<?php
echo $arr[foo(true)];
echo $arr[somefunc($bar)];
?>
]]>
</programlisting>
@ -1437,7 +1564,8 @@ $error_descriptions[8] = "This is just an informal notice";
because <literal>E_ERROR</literal> equals <literal>1</literal>, etc.
</para>
<para>
Then, how is it possible that <literal>$foo[bar]</literal> works?
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
@ -1455,48 +1583,14 @@ $error_descriptions[8] = "This is just an informal notice";
<literal>default</literal> this way, since they are special
<link linkend="reserved">reserved keywords</link>.
</para>
<note>
<para>
When you turn <link linkend="function.error-reporting"
>error_reporting</link> to <literal>E_ALL</literal>,
you will see that PHP generates notices whenever an
<literal>index</literal> is used which is not defined.
Consider this script:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Turn on the display of all errors
error_reporting(E_ALL);
// Define the test array
$abc = array("x" => "y");
// Access element with the *bad* method
echo $abc[x];
?>
]]>
</programlisting>
</informalexample>
The output is:
<informalexample>
<programlisting>
<![CDATA[
<br />
<b>Notice</b>: Use of undefined constant x - assumed 'x' in <b>/path/to/script.php</b> on
line <b>10</b><br />
]]>
</programlisting>
</informalexample>
</para>
</note>
<note>
<simpara>
Inside a double-quoted <type>string</type>, another syntax
is valid. See <link linkend="language.types.string.parsing"
>variable parsing in strings</link> for more details.
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>
@ -1507,15 +1601,17 @@ line <b>10</b><br />
<title>Converting to array</title>
<para>
For any of the types: integer, float, string, boolean and resource,
if you convert a value to an array, you get an array with one element
(with index 0), which is the scalar value you started with.
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 object to an array, you get the properties (member
variables) of that object as the array's elements. The keys are the
member variable names.
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>