Path: csiph.com!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Arno Welzel Newsgroups: comp.lang.php Subject: Re: Using count() as an array index Date: Mon, 18 Jun 2012 09:46:15 +0200 Organization: A noiseless patient Spider Lines: 55 Message-ID: <4FDEDCC7.4010002@arnowelzel.de> References: Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: 7bit Injection-Info: mx04.eternal-september.org; posting-host="uO9Sccelu4tfD+GMr79Efw"; logging-data="26557"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/r3rhoqbOsASQM3KwngPnss0xLs1cEZfw=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20120428 Thunderbird/12.0.1 In-Reply-To: Cancel-Lock: sha1:imXFLCmKVDw7fiERoUal+OY7tlA= Xref: csiph.com comp.lang.php:6358 Jerry Stuckle, 16.06.2012 20:44: > On 6/16/2012 1:56 PM, Martin Leese wrote: >> Chuck Anderson wrote: >> >>> You can not use a function call within a quoted string. >>> >>> You should use: >>> >>> echo $anArray[count($array)] . "\n"; >> >> Thank you. I actually understood this >> explanation. >> > > Actually, you can easily use a function call within a quoted string, but > since it is not a simple variable, you need to use curly braces, i.e. > > $anArray[1] = "This is element one"; > $anArray[2] = "This is element two"; > $anArray[3] = "This is the last element"; > echo "{$anArray[count($anArray)]}\n"; > ?> > > prints "This is the last element" (without the quotes, of course). Please compare: $anArray[count($array)] . "\n"; "{$anArray[count($anArray)]}\n"; You see the difference? Your suggestion is longer (even whitespaces which can me omitted) and totally unreadable for people you are not familiar with this. > Be aware, though - the typical array in PHP starts counting at 0, not 1. > So an array of 3 elements would be numbered 0, 1 and 2. In this case, > an element with an index of 3 (count($anArray)) is not set (and will > give a warning if you try to use it). ACK. > You need to get used to this idea; it's used throughout PHP. Just because something is possible does not mean you have to use it ;-) Curly braces should only be used for code blocks and not to replace string concatenation. -- Arno Welzel http://arnowelzel.de http://de-rec-fahrrad.de