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.66666666667 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.
©2024, by Bill Sanders, all rights reserved.
This domain had 3,510 different visits in the last 30 days.
http://www.sandersongs.com/PHPsqlCourse/PHPadv13.php
This page was last modified on our server on 11 Jul 2021
and last refreshed on our server at 9:09 am, UTC
This file took 0.01039 seconds to process.