...

View Full Version : Trying to use variable to call image .....



Buffmin
04-25-2012, 06:55 PM
Hello.

I have a php page.

On this page, I break out and use html to call an image.
Rather than hand code the folder name in the image path, I would rather refer to the folder using a php variable.

(The reason is that there will be multiple similar pages, refering to different geographical areas, and each one has it's variable set at the top of the page.

The variable (that refers to the folder is called $area). In this case $area= "Apache Junction"

First, I will show you the code as it is now (and does work).
Then I will show you the code that I tried (and doesn't work).
PS: do not get a php error, but it does not find the image)

I appreciate any help. Buffmin

Current Code:


<img src="images/Apache Junction/image1.jpg">


PHP code that DOES NOT work


<img src="images/<? $area ?>/coulter13.jpg" title="">

PS Again.... It seems like maybe it is because I have to leave a space on each side of the variable name?
(I have to leave the spaces or in Dreamweaver, the tags turn from red to blue)

Fou-Lu
04-25-2012, 08:23 PM
No, the whitespace itself is irrelevant in PHP, so do whatever to make your editor happy. The use is incorrect though:


<?php

$variable
?>

Won't result in anything. You need to actually print it: <?php echo $area;?>. Double check as well that it doesn't show as PHP in the html source and link. If it does, make sure the page is a .php script or set to process as PHP. Always use full <?php tags and never short tags with <? (although they will officially make <?= a shortcut echo valid in any PHP build, I don't think that its actually happened yet).

Although you do have me slightly confused. If this variable is just a path to an image, then that image path will show in its entirety in the link.


I stand corrected. <?= will now work regardless of short_open_tag directive as of PHP 5.4.0 (which is brand new mind you).

Buffmin
04-25-2012, 09:49 PM
Ahh. perfect! Thanks for the help (and tips). I forgot about using the echo.
Buffmin

Dormilich
04-26-2012, 08:56 AM
if you have more images of this sort, consider using a printf() function (which also doesn’t require you to break out of PHP).

ex.

// define an image template
define("IMG", '<img src="images/%s/image%d.jpg">');

// somewhere in your code
printf(IMG, $folder1, 1);

// somewhere else
printf(IMG, $folder3, 3);

Buffmin
04-26-2012, 05:29 PM
Good idea. Thank you!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum