Jump to content

PHP Correction on your site


.Ben

Recommended Posts

Hello,

 

I realized that you have made a mistake on the PHP code on the Arrays lesson. http://www.phpfreaks.com/tutorials/42/1.php

 

On this code example:

 

<?php
$bakery = array(
    "cherry" => "5.00",
    "apple" => "4.00",
    "other" => "2.00",
);
echo "cherry pie costs $bakery['cherry'], apple pie costs $bakery['apple'], and that other pie costs $bakery['other'].";
?>

 

Correction:

 

<?php
$bakery = array(
    "cherry" => "5.00",
    "apple" => "4.00",
    "other" => "2.00",
);
echo "cherry pie costs ".$bakery['cherry'].", apple pie costs ".$bakery['apple'].", and that other pie costs ".$bakery['other'].".";
?> 

Link to comment
Share on other sites

the original method also works. the double quotes for a string (") instead of singles (') allow you to embed variables like this. i actually use the original way quite a bit, however I seperate them from the content using { } like:

 

<?php
$string = "my name is {$myname['forename']} {$myname['surname']}";
?>

just to avoid any confusion.

 

either way, both ways are valid and will work.

Link to comment
Share on other sites

For sake of argument, though, I will add that the original posted "error" will produce warnings; however, it will not break your script. If you use an array value within double quotes, you need to either encapsulate it within brackets like redbullmarky shows, or leave out the quotes around the key all together:

<?php
// This will produce warnings
echo "cherry pie costs $bakery['cherry'], apple pie costs $bakery['apple'], and that other pie costs $bakery['other'].";

// The following are all acceptable (no warnings or errors)
echo "cherry pie costs $bakery[cherry], apple pie costs $bakery[apple], and that other pie costs $bakery[other].";
echo "cherry pie costs {$bakery['cherry']}, apple pie costs {$bakery['apple']}, and that other pie costs {$bakery['other']}.";
echo "cherry pie costs " . $bakery['cherry'] . ", apple pie costs " . $bakery['apple'] . ", and that other pie costs " . $bakery['other'] . ".";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.