SlideShare a Scribd company logo
PHP Basics

Nelson Ochieng
Instruction Separation
•   PHP requires instructions to be terminated with a semicolon at the end of
    each statement.
•   The closing tag of a block of PHP code automatically implies a semicolon;

<?php
    echo 'This is a test';
?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';
Comments
<?php
    echo 'This is a test'; //       This is a one-line c++ style comment


     /* This is a multi line comment
        yet another line of comment */

     echo 'This is yet another test';
     echo 'One Final Test'; # This is a one-line   shell-style comment

?>
Types
•   Some types that PHP supports.
•   Four scalar types:
     –   boolean
     –   integer
     –   float (floating-point number, aka double)
     –   string
•   Two compound types:
     –   array
     –   object
•   And finally three special types:
     –   resource
     –   NULL
<?php
$a_bool = TRUE;   // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12;     // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}
// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}
?>
Booleans
•   A boolean expression expresses a truth value. Can be TRUE or FALSE
<?php
$foo = True; // assign the value TRUE to $foo
?>
<?php
// == is an operator which tests
// 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 this can be used with exactly the same meaning:
if ($show_separators) {
    echo "<hr>n";
}
Integers
•   An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
•   Integers can be specified in decimal (base 10), hexadecimal (base 16), octal
    (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).
•   To use octal notation, precede the number with a 0 (zero). To use
    hexadecimal notation precede the number with 0x. To use binary notation
    precede the number with 0b.
<?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)
?>
Strings
•   A string is series of characters, where a character is the same as a byte.
•   A string literal can be specified in four different ways:
     –   single quoted
     –   double quoted
     –   heredoc syntax
     –   nowdoc syntax (since PHP 5.3.0)
Single Quoted
<?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';
   ?>
Double Quoted
• The most important feature of double-quoted strings is the fact that variable
   names will be expanded.
Heredoc
• A third way to delimit strings is the heredoc syntax: <<<. After this operator,
   an identifier is provided, then a newline. The string itself follows, and then
   the same identifier again to close the quotation.
• The closing identifier must begin in the first column of the line. Also, the
   identifier 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.
Nowdoc
• A nowdoc is identified with the same <<< sequence used for heredocs, but
   the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All
   the rules for heredoc identifiers also apply to nowdoc identifiers, especially
   those regarding the appearance of the closing identifier.
Arrays
•   An array in PHP is actually an ordered map.
•   A map is a type that associates values to keys.
•   This type is optimized for several different uses:
     –   Array
     –    list (vector)
     –   hash table (an implementation of a map)
     –   Dictionary
     –   Collection
     –   Stack
     –   Queue
     •    As array values can be other arrays, trees and multidimensional arrays
         are also possible.
Specifying an Array
•   An array can be created using the array() language construct.
•   It takes any number of comma-separated key => value pairs as arguments.

array(
    key => value,
    key2 => value2,
    key3 => value3,
    ...
)
Specifying an Array
•   As of PHP 5.4 you can also use the short array syntax, which replaces
    array() with [].
<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);
// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>
•   The key can either be an integer or a string. The value can be of any type.
Accessing array elements with square
               bracket syntax
•   Array elements can be accessed using the array[key] syntax.
<?php
  $array = array(
      "foo" => "bar",
      42     => 24,
      "multi" => array(
           "dimensional" => array(
                "array" => "foo"
           )
      )
  );
    var_dump($array["foo"]);
    var_dump($array[42]);
    var_dump($array["multi"]["dimensional"]["array"]);
    ?>
Creating/modifying with square bracket
                syntax
•   An existing array can be modified by explicitly setting values in it.
•   This is done by assigning values to the array, specifying the key in brackets.
    The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
•   To change a certain value, assign a new value to that element using its key.
•   To remove a key/value pair, call the unset() function on it.
Objects
•   Object Initialization
     –   To create a new object, use the new statement to instantiate a class:
<?php
  class foo
  {
      function do_foo()
      {
          echo "Doing foo."; 
      }
  }

    $bar = new foo;
    $bar->do_foo();
    ?> 
Resources
•   A resource is a special variable, holding a reference to an external resource.
    Resources are created and used by special functions
Null
•   The special NULL value represents a variable with no value.

More Related Content

PPT
Class 5 - PHP Strings
PPTX
Introduction in php part 2
PPTX
Introduction in php
PDF
Php Tutorials for Beginners
PPTX
Object-Oriented Programming with PHP (part 1)
PDF
Introduction to Python for Plone developers
Class 5 - PHP Strings
Introduction in php part 2
Introduction in php
Php Tutorials for Beginners
Object-Oriented Programming with PHP (part 1)
Introduction to Python for Plone developers

What's hot (19)

PPT
Class 2 - Introduction to PHP
PPT
Antlr V3
PPTX
php string part 4
PPTX
Subroutines in perl
PPTX
PHP Powerpoint -- Teach PHP with this
PPTX
Regular Expressions in PHP
PPT
Class 3 - PHP Functions
PDF
Functions in PHP
PPT
Php Chapter 2 3 Training
ODP
Introduction to Perl - Day 1
ODP
perl usage at database applications
PPTX
Strings,patterns and regular expressions in perl
PPTX
PHP Basics
PPTX
Chap1introppt2php(finally done)
PDF
Perl programming language
PPTX
Bioinformatics p1-perl-introduction v2013
PPT
Perl Presentation
Class 2 - Introduction to PHP
Antlr V3
php string part 4
Subroutines in perl
PHP Powerpoint -- Teach PHP with this
Regular Expressions in PHP
Class 3 - PHP Functions
Functions in PHP
Php Chapter 2 3 Training
Introduction to Perl - Day 1
perl usage at database applications
Strings,patterns and regular expressions in perl
PHP Basics
Chap1introppt2php(finally done)
Perl programming language
Bioinformatics p1-perl-introduction v2013
Perl Presentation
Ad

Viewers also liked (20)

PDF
Php tutorial
PDF
PHP traits, treat or threat?
ODP
The why and how of moving to PHP 5.5/5.6
DOCX
PPTX
PHP slides
PPTX
Subsidio i.1 demanda actual
PPTX
Enquête Doctipharma : Les français et la vente de médicaments sur internet
PPTX
AOA - Annual OMEL Conference Encourages Osteopathic Discourse
PPTX
Tudatos márkaépítés
PDF
Estrategias de comunicación para el ciberactivismo
PDF
الإرشاد التربوي والنفسي في المؤسسات التعليمية
PDF
Homoeopathic Home Prescribing Class 18th October 2014
PPTX
מחדד 05.03
KEY
JavaScript Craftsmanship: Why JavaScript is Worthy of TDD
PDF
Call me VL-11 28.11.2012 Ole Kassow
PDF
Virtualni svet Second Life
KEY
Design persuasivo: alcuni esempi
PPTX
Почему не работают корпоративные социальные сети?
PPT
урок знам и мога
Php tutorial
PHP traits, treat or threat?
The why and how of moving to PHP 5.5/5.6
PHP slides
Subsidio i.1 demanda actual
Enquête Doctipharma : Les français et la vente de médicaments sur internet
AOA - Annual OMEL Conference Encourages Osteopathic Discourse
Tudatos márkaépítés
Estrategias de comunicación para el ciberactivismo
الإرشاد التربوي والنفسي في المؤسسات التعليمية
Homoeopathic Home Prescribing Class 18th October 2014
מחדד 05.03
JavaScript Craftsmanship: Why JavaScript is Worthy of TDD
Call me VL-11 28.11.2012 Ole Kassow
Virtualni svet Second Life
Design persuasivo: alcuni esempi
Почему не работают корпоративные социальные сети?
урок знам и мога
Ad

Similar to Php basics (20)

PDF
Php Crash Course - Macq Electronique 2010
PPTX
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT 1 (7).pptx
PPTX
UNIT 1 (7).pptx
PPTX
PPT
PHP and MySQL with snapshots
PPTX
PHP Course (Basic to Advance)
PPTX
Lesson 2 php data types
PDF
Web 8 | Introduction to PHP
PPSX
DIWE - Advanced PHP Concepts
DOC
php&mysql with Ethical Hacking
PPT
PHP-01-Overview.pptfreeforeveryonecomenow
PPTX
Ch1(introduction to php)
PPT
PHP Scripting
PPTX
PHP Basics
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
PDF
Introduction to PHP_Slides by Lesley_Bonyo.pdf
PPTX
Lecture 2 php basics (1)
PPT
PHP - Introduction to PHP - Mazenet Solution
Php Crash Course - Macq Electronique 2010
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT 1 (7).pptx
UNIT 1 (7).pptx
PHP and MySQL with snapshots
PHP Course (Basic to Advance)
Lesson 2 php data types
Web 8 | Introduction to PHP
DIWE - Advanced PHP Concepts
php&mysql with Ethical Hacking
PHP-01-Overview.pptfreeforeveryonecomenow
Ch1(introduction to php)
PHP Scripting
PHP Basics
Introduction to PHP_ Lexical structure_Array_Function_String
Introduction to PHP_Slides by Lesley_Bonyo.pdf
Lecture 2 php basics (1)
PHP - Introduction to PHP - Mazenet Solution

Recently uploaded (20)

PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Approach and Philosophy of On baking technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Spectroscopy.pptx food analysis technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Cloud computing and distributed systems.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
Approach and Philosophy of On baking technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectroscopy.pptx food analysis technology
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Cloud computing and distributed systems.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
cuic standard and advanced reporting.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
gpt5_lecture_notes_comprehensive_20250812015547.pdf

Php basics

  • 2. Instruction Separation • PHP requires instructions to be terminated with a semicolon at the end of each statement. • The closing tag of a block of PHP code automatically implies a semicolon; <?php echo 'This is a test'; ?> <?php echo 'This is a test' ?> <?php echo 'We omitted the last closing tag';
  • 3. Comments <?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shell-style comment ?>
  • 4. Types • Some types that PHP supports. • Four scalar types: – boolean – integer – float (floating-point number, aka double) – string • Two compound types: – array – object • And finally three special types: – resource – NULL
  • 5. <?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $a_bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool"; } ?>
  • 6. Booleans • A boolean expression expresses a truth value. Can be TRUE or FALSE <?php $foo = True; // assign the value TRUE to $foo ?> <?php // == is an operator which tests // 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 this can be used with exactly the same meaning: if ($show_separators) { echo "<hr>n"; }
  • 7. Integers • An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. • Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). • To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b. <?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) ?>
  • 8. Strings • A string is series of characters, where a character is the same as a byte. • A string literal can be specified in four different ways: – single quoted – double quoted – heredoc syntax – nowdoc syntax (since PHP 5.3.0)
  • 9. Single Quoted <?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'; ?>
  • 10. Double Quoted • The most important feature of double-quoted strings is the fact that variable names will be expanded. Heredoc • A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. • The closing identifier must begin in the first column of the line. Also, the identifier 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. Nowdoc • A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
  • 11. Arrays • An array in PHP is actually an ordered map. • A map is a type that associates values to keys. • This type is optimized for several different uses: – Array – list (vector) – hash table (an implementation of a map) – Dictionary – Collection – Stack – Queue • As array values can be other arrays, trees and multidimensional arrays are also possible.
  • 12. Specifying an Array • An array can be created using the array() language construct. • It takes any number of comma-separated key => value pairs as arguments. array( key => value, key2 => value2, key3 => value3, ... )
  • 13. Specifying an Array • As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. <?php $array = array( "foo" => "bar", "bar" => "foo", ); // as of PHP 5.4 $array = [ "foo" => "bar", "bar" => "foo", ]; ?> • The key can either be an integer or a string. The value can be of any type.
  • 14. Accessing array elements with square bracket syntax • Array elements can be accessed using the array[key] syntax. <?php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?>
  • 15. Creating/modifying with square bracket syntax • An existing array can be modified by explicitly setting values in it. • This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type • To change a certain value, assign a new value to that element using its key. • To remove a key/value pair, call the unset() function on it.
  • 16. Objects • Object Initialization – To create a new object, use the new statement to instantiate a class: <?php class foo {     function do_foo()     {         echo "Doing foo.";      } } $bar = new foo; $bar->do_foo(); ?> 
  • 17. Resources • A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions
  • 18. Null • The special NULL value represents a variable with no value.

Editor's Notes

  • #3: You do not need to have a semicolon terminating the last line of a PHP block. The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
  • #4: The &quot;one-line&quot; comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?&gt; or # ... ?&gt; WILL be printed: ?&gt; breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. &lt;h1&gt;This is an &lt;?php # echo &apos;simple&apos;;?&gt; example&lt;/h1&gt; &lt;p&gt;The header above will say &apos;This is an example&apos;.&lt;/p&gt; EXERCISE when the comment string contains &apos;?&gt;&apos;, you should be careful. e.g. output code 1= code 2 is different with code 3 1. with // &lt;?php // echo &apos;&lt;?php ?&gt;&apos;; ?&gt; 2. with # &lt;?php // echo &apos;&lt;?php ?&gt;&apos;; ?&gt; 3. with /* */ &lt;?php /* echo &apos;&lt;?php ?&gt;&apos;;*/ ?&gt; The following code will cause a parse error! the ?&gt; in //?&gt; is not treated as commented text, this is a result of having to handle code on one line such as &lt;?php echo &apos;something&apos;; //comment ?&gt; &lt;?php if(1==1) { //?&gt; } ?&gt;
  • #5: The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used. To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:
  • #6: To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.
  • #7: Typically, the result of an operator which returns a boolean value is passed on to a control structure.
  • #8: The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Example #3 Integer overflow on a 32-bit system &lt;?php $large_number = 2147483647; var_dump($large_number); // int(2147483647) $large_number = 2147483648; var_dump($large_number); // float(2147483648) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // float(50000000000) ?&gt; Example #4 Integer overflow on a 64-bit system &lt;?php $large_number = 9223372036854775807; var_dump($large_number); // int(9223372036854775807) $large_number = 9223372036854775808; var_dump($large_number); // float(9.2233720368548E+18) $million = 1000000; $large_number = 50000000000000 * $million; var_dump($large_number); // float(5.0E+19) ?&gt; EXERCISE There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding. &lt;?php var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ?&gt;
  • #11: &lt;?php $str = &lt;&lt;&lt;EOD Example of string spanning multiple lines using heredoc syntax. EOD; &lt;?php $str = &lt;&lt;&lt;&apos;EOD&apos; Example of string spanning multiple lines using nowdoc syntax. EOD;
  • #14: EXERCISE If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. Example #2 Type Casting and Overwriting example &lt;?php $array = array( 1 =&gt; &quot;a&quot;, &quot;1&quot; =&gt; &quot;b&quot;, 1.5 =&gt; &quot;c&quot;, true =&gt; &quot;d&quot;, ); var_dump($array); ?&gt; The above example will output: array(1) { [1]=&gt; string(1) &quot;d&quot; } As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value &quot;d&quot; is the only one left over. PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. Example #3 Mixed integer and string keys &lt;?php $array = array( &quot;foo&quot; =&gt; &quot;bar&quot;, &quot;bar&quot; =&gt; &quot;foo&quot;, 100 =&gt; -100, -100 =&gt; 100, ); var_dump($array); ?&gt; The above example will output: array(4) { [&quot;foo&quot;]=&gt; string(3) &quot;bar&quot; [&quot;bar&quot;]=&gt; string(3) &quot;foo&quot; [100]=&gt; int(-100) [-100]=&gt; int(100) } The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key. Example #4 Indexed arrays without key &lt;?php $array = array(&quot;foo&quot;, &quot;bar&quot;, &quot;hallo&quot;, &quot;world&quot;); var_dump($array); ?&gt; The above example will output: array(4) { [0]=&gt; string(3) &quot;foo&quot; [1]=&gt; string(3) &quot;bar&quot; [2]=&gt; string(5) &quot;hallo&quot; [3]=&gt; string(5) &quot;world&quot; } It is possible to specify the key only for some elements and leave it out for others: Example #5 Keys not on all elements &lt;?php $array = array( &quot;a&quot;, &quot;b&quot;, 6 =&gt; &quot;c&quot;, &quot;d&quot;, ); var_dump($array); ?&gt; The above example will output: array(4) { [0]=&gt; string(1) &quot;a&quot; [1]=&gt; string(1) &quot;b&quot; [6]=&gt; string(1) &quot;c&quot; [7]=&gt; string(1) &quot;d&quot; } As you can see the last value &quot;d&quot; was assigned the key 7. This is because the largest integer key before that was 6. Accessing array elements with square bracket syntax Array elements can be accessed using the array[key] syntax. Example #6 Accessing array elements &lt;?php $array = array( &quot;foo&quot; =&gt; &quot;bar&quot;, 42 =&gt; 24, &quot;multi&quot; =&gt; array( &quot;dimensional&quot; =&gt; array( &quot;array&quot; =&gt; &quot;foo&quot; ) ) ); var_dump($array[&quot;foo&quot;]); var_dump($array[42]); var_dump($array[&quot;multi&quot;][&quot;dimensional&quot;][&quot;array&quot;]); ?&gt; The above example will output: string(3) &quot;bar&quot; int(24) string(3) &quot;foo&quot; Creating/modifying with square bracket syntax An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type If $arr doesn&apos;t exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. &lt;?php $arr = array(5 =&gt; 1, 12 =&gt; 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr[&quot;x&quot;] = 42; // This adds a new element to // the array with key &quot;x&quot; unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?&gt; Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero). Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: &lt;?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 =&gt; $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?&gt; The above example will output: Array ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 [3] =&gt; 4 [4] =&gt; 5 ) Array ( ) Array ( [5] =&gt; 6 ) Array ( [0] =&gt; 6 [1] =&gt; 7 )
  • #15: Output string(3) &quot;bar&quot; int(24) string(3) &quot;foo“ Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).
  • #16: &lt;?php $arr = array(5 =&gt; 1, 12 =&gt; 2); $arr[] = 56;    // This is the same as $arr[13] = 56;                 // at this point of the script $arr[&quot;x&quot;] = 42; // This adds a new element to                 // the array with key &quot;x&quot;                  unset($arr[5]); // This removes the element from the array unset($arr);    // This deletes the whole array ?&gt;