PHP Advanced Concepts

Construct Tricks

You can use parentheses ' ( ) ' and curly braces ' { } ' to group characters together as a unit in PHP. Look at the following examples:

<?php $target = "Electrical Plant"; $oldTargets = array("Electrical Plant", "Military HQ", "Munitions Plant"); $newTargets = array("one"=>"Electrical Plant", "two"=>"Military HQ", "three"=>"Munitions Plant); echo "We hit the $targets."; // produces: We hit the . echo "We hit the $target(s)."; // produces: We hit the Electrical Plant(s). echo "We hit the ${target}s."; // produces: We hit the Electrical Plants. echo "We hit the {$target}s."; // produces: We hit the Electrical Plants. echo "We hit the { $target}s."; // produces: We hit the { Electrical Plant}s. echo "We hit the $oldTargets[0]s."; // produces: We hit the Electrical Plants. echo "We hit the {$oldTargets[1]}s."; // produces: We hit the Military HQs. echo "We hit the ".$oldTargets[2]."s."; // produces: We hit the Munitions Plants. echo "We hit the $newTargets['one']s."; // produces: Parse error: ... echo "We hit the {$newTargets['two']}s."; // produces: We hit the Military HQs. echo "We hit the ".$newTargets['three']."s."; // produces: We hit the Munitions Plants. echo 5/3+2-1; // produces: 2.6666666666667 echo (5/(3+2))-1; // produces: 0 ?>

Characters within strings may be accessed by specifying the zero-based offset of the desired character after the string in curly braces.

<?php $string = "Duty, Honor, Country"; echo $string{0}; // produces: D echo $string{strlen($string)-1}; // produces: y echo $string{2,8}; // produces: Parse error: ... echo $string{12-4}; // produces: n ?>


Quote Tricks   < <  PREVIOUS   Table of Contents NEXT  > >   Reference Links

Developed with HTML-Kit
Sandersongs Web Tutorials
Contact the Webmasterwith comments.
©2017, by Bill Sanders, all rights reserved.
This domain had 4,010 different visits in the last 30 days.
435,487 hits on this domain since 24 Nov 2006.
http://sandersongs.com/PHPsqlCourse/PHPadv13.php
This page was last modified on our server on 4 Jun 2008
and last refreshed on our server at 12:33 pm, MST
This file took 0.00854 seconds to process.