PDA

View Full Version : [PHP] Defining a Variable (yea yea Paul shh)


Pauly
November 21st, 2004, 06:35
Is it possible to do the below? Also if it's incorrect can you correct it for me?

$gallery = "<img src=\"images/misc/gallery.gif\" class=\"fl\" />"

the_pm
November 21st, 2004, 06:43
Perhaps divulging the coding language in question would be helpful ;)

For example, this probably won't work too well in JavaScript...

Pauly
November 21st, 2004, 06:47
Showing me up ;) lol Sorry I'm in a state of mind where I assume everyone is on the same page as me.

PHP would help :)

the_pm
November 21st, 2004, 06:57
You're in PHP, which means you're already ahead of me. I'll step aside - I just figured I'd clarify for those more mentally fortunate than I ;)

Pauly
November 21st, 2004, 07:10
I read something over at w3schools but I'm doing this with vB too, what I really would like to do is this;


$pageimg =
IF page=gallery.php SHOW <img src="images/misc/gallery.gif" />
OR
IF page=cars.php SHOW <img src="images/misc/car.gif" />


But obviously it's not that simple.

ethicaldesign
November 21st, 2004, 13:06
Is it possible to do the below? Also if it's incorrect can you correct it for me?

$gallery = "<img src=\"images/misc/gallery.gif\" class=\"fl\" />"

That would work as far as I can see, but isn't very efficient.

It should execute faster if you drop the double quotes from the outside and use single quotes. This won't do any evaluation of the string and your double quotes will be treat as straight characters in the string (you only need to escape double quotes in a double quoted string).

Something like:

$gallery = '<img src="images/misc/gallery.gif" class="fl" />';

would work faster I believe (and be a bit more readable as an added benefit).

The way I would sometimes tend to do it (often because I have variable's that I want to include and don't want to evaluate them within double quotes ) would be something like:

$gallery ='<img src='.chr(34).$myimage.chr(34).' class='.chr(34).$myclass.chr(34).' />';

You can use chr(34) to represent the double quote character when building strings using variables, without using double quotes to evaluate them. Which method is the fastest in that case I guess might depend upon what sort of evaluation might be taking place in the double quoted string compared to building it this way. Not 100% sure about that though (would be cool if someone reading this knows!).

Probably not quite as efficient as the first example in your particular case, but might be helpful if you want to build strings containing both variables and double quote characters.

Not really relevant to your example exactly, but just mention it incase you want to use variables in it.

ethicaldesign
November 21st, 2004, 13:23
I read something over at w3schools but I'm doing this with vB too, what I really would like to do is this;


$pageimg =
IF page=gallery.php SHOW <img src="images/misc/gallery.gif" />
OR
IF page=cars.php SHOW <img src="images/misc/car.gif" />


But obviously it's not that simple.

If you've got a several of those conditions, and particularly if there might be the scope that you want to do more than display an image based upon the page name, you should find that a switch works faster and looks nicer to read . The way I would tend to do that:



$path='images/misc/';

switch ($page)
{

case 'gallery.php':
$img='gallery.gif';
break;

case 'cars.php':
$img='cars.gif';
break;
}

$pageimg = '<img src='.chr(34).$path.$img.chr(34).' />';



This is assuming that there's the possibility that there will be more than 2 cases of $page, and that $page is something that you have defined somewhere (you don't specify where that variable is coming from).

As far as I know, switches work much faster than lots of if conditions. Not completely sure if that is the case where there are only two. In your example it looks like there would be the potential scope for more than two pages, and that you could potentially want to do something more than define an image at some point based upon the evaluation of your page variable, so i would tend to code it this way from the start to save time later.

This is also interesting to me (like your first question) of whether a switch would prove faster than a series of IF's if there are only 2 conditions. Perhaps someone reading this could clarify that?

This approach also assumes that the name of the gif and the name of the page might vary (there might be a better way to do it if they are both the same by simply using the page name minus the .php at the end as your image name - which would remove the need to test conditions - however this might be less flexible).

Hope that's some help anyway. Been up all night working so getting a bit tired now (sorry if my explanation is a bit long winded - about to nodd off here and I know I have a tendency to ramble on a bit when I'm tired - see - I'm doing it now!).

ethicaldesign
November 21st, 2004, 13:25
P.S. Forgot to mention - I separated the path into another variable so that if your image path changes at any point, you don't have to go through several lines of code modifying your output. Just one path variable to change. In reality I would probably have put the path into a constant definition in a preference file somewhere that's included in your page but for the sake of a simple example I didn't want to ramble on too much about that.

sonicgroup
November 21st, 2004, 14:39
A switch, in this case, is probably your best bet because you are tesing the same variable over and over for different values.

Another way, just to throw it out there: shorthand IF statements:

[syntax:04a8b79195="php"]$gallery = ($page == 'gallery') ? '<img src="images/misc/gallery.gif" class="fl" />' : '<img src="images/misc/car.gif" class="fl" />';[/syntax:04a8b79195]

ethicaldesign
November 21st, 2004, 15:10
A switch, in this case, is probably your best bet because you are tesing the same variable over and over for different values.

Another way, just to throw it out there: shorthand IF statements:

[syntax:70f479bcd0="php"]$gallery = ($page == 'gallery') ? '<img src="images/misc/gallery.gif" class="fl" />' : '<img src="images/misc/car.gif" class="fl" />';[/syntax:70f479bcd0]

That's a nice succint way of writing it. :) (and I notice that syntax tag here is pretty cool!).

Do you know if that would execute faster than my example using a switch (assuming there were only 2 cases and I hadn't bothered to define the path seperately and had defined the $pageimg directly within the cases themselves like your if/else rather than at the end)?

I know the switch can accomodate several possibilities and will likely execute faster when that's the case, but I'm not sure if there are only 2. Perhaps your method is faster in that case (seems to me it might be as it's more succinct but I'm unsure)?

sonicgroup
November 21st, 2004, 23:32
Assuming a binary condition, yes, an if/else will run faster than a switch, and to take that further, I've not done any extensive testing with the long vs short way of writing if statements. I just find that in the case of assigning a result to a variable, the short way is easier, more succinct, and easier to read.

The only disadvantage to the short way is that you can only use it for assignments. You wouldn't be able to embed a lot of function calls inside it.

Pauly
November 22nd, 2004, 14:27
Because I'm using vB I posted the same question over at vBulletin.org and I was told using this;

if (THIS_SCRIPT == 'website_articles') $showimage = '<img src="http://www.opaqueice.com/images/blue/misc/articles.gif" alt="$vboptions[bbtitle]" />';

Would work as I needed. However, now I'm faced with how to use an else statement, so that if the "THIS_SCRIPT" bit isn't defined for a page but the variable appears, a default image will be displayed. Any ideas?

sonicgroup
November 22nd, 2004, 14:50
[syntax:47b73778b7="php"]
if (THIS_SCRIPT == 'website_articles') {
$showimage = '<img src="http://www.opaqueice.com/images/blue/misc/articles.gif" alt="$vboptions[bbtitle]" />';
} else {
$showimage = '<img src="http://www.opaqueice.com/images/blue/misc/OTHERIMAGE.gif" alt="$vboptions[bbtitle]" />';
}
[/syntax:47b73778b7]

ethicaldesign
November 22nd, 2004, 15:20
I think you might need to use an elseif there to check that it's not defined for the second bit if you do it this way otherwise if THIS_SCRIPT== something other than website_articles (but is defined) it'll display the other image when perhaps it shouldn't be (depending on what you're aiming for).

If you are going to have more than one case (aswell as the not defined check) I would put it in a switch like above.

THIS_SCRIPT is just a constant so can be treat more or less like a regular variable (at least in this context).

Something like the example I posted above but replace $page with THIS_SCRIPT, change the cases from the php pages to 'website_articles' etc. and add another case at the end to check whether THIS_SCRIPT is undefined/empty for displaying your OTHERIMAGE.gif in the case of none of the other conditions being used (rather than using the keyword 'case' use 'default' though).

There's a brief overview of these structures here: http://www.w3schools.com/php/php_conditionals.asp that you might find helpful.

Pauly
November 22nd, 2004, 16:18
I used dave's little bit (thanks Dave) because it's what I'm familiar with :)

Thanks for that link too, I've read it before but it didn't hurt to refresh my memory ;)

Also, how would I define a variable within a variable? I have this script; $view_cat="All Oi News"; @include "news/news.php";

But doing the below doesn't work :(

// BELOW IS THE NEWS SCRIPT
$fp_news = $view_cat="All Oi News"; @include "news/news.php";

ethicaldesign
November 23rd, 2004, 03:47
I'm not completely sure what you want to do there. I'm guessing that you want to define a new variable that contains some text, and another variable.

If that's the case you can use a full stop to concatenate the string. For example:


$category='Web Development';
$titletext='Welcome to the '.$category.' category';
echo $titletext;




will produce:

Welcome to the Web Development category.

I'm not quite sure if that's what you mean though. If you want to have two variables defined containing the string "All Oi News" then you could simply use:

$fp_news=$view_cat;

after you've defined $view_cat. This seems a little wasteful however using two variables to contain the same value (I'm guessing if this is what you want to do it's because news.php needs to use the variable $fp_news?)

Your code above should work in the same way. For example:


$fp_news = $view_cat="All Oi News";

echo $fp_news;


will display :

All Oi News

as expected. Not sure of the benefits of writing it like that though except perhaps saving a little typing because it'll still need to parse two definitions so don't think it would execute any faster (could be wrong). I would tend to use the same variable name to save wasting resources for duplicates, or if I absolutely had to have two variables the same I would probably do it over two lines. Your way does appear to work though.

What's the problem exactly? That $fp_news isn't being defined as you expect or that the news script isn't picking it up? Or that the news script isn't being loaded at all? If it's the latter you could try:

require('news/news.php');

Miss off the @ symbol, because I think that'll have the effect of surpressing a warning if the file isn't loading correctly (perhaps the path is wrong or something?).

You should really try to get out of the habit of using double quotes unless they're absolutely necessary though. This is something I did when I first started with php (largely because a lot of the scripts I looked at as learning exercises did it that way) as it's going to slow down your code unnecessarily and will be something you regret (and will possibly feel compelled to spend time going back and fixing later if you're anything like me). Don't mean to be a nag, but I know how hard it is to break bad programming habits (which I'm sure everyone has to some extent) so it always saves a lot of time to get into the habit of doing things the right way wherever possible from the start.

Hope that's some help anyway. If not if you could let me know a little more about the problem I might be able to help. :)

Pauly
November 23rd, 2004, 09:59
You should really try to get out of the habit of using double quotes unless they're absolutely necessary though. This is something I did when I first started with php (largely because a lot of the scripts I looked at as learning exercises did it that way)

Yes, the scripts I'm looking at do it.

The problem I'm having you didn't really touch on however, although I appreciate the long explanation :)

The news script I'm using says use;

$view_cat="All Oi News"; @include "news/news.php";

I can only assume this is to detect which category of news it's to display from news/news.php. $fp_news is the variable I would like to use to include the news into my page.

I think it will be easier if I just add $view_cat='All Oi News'; to my news/news.php file :)

ethicaldesign
November 23rd, 2004, 10:16
You should really try to get out of the habit of using double quotes unless they're absolutely necessary though. This is something I did when I first started with php (largely because a lot of the scripts I looked at as learning exercises did it that way)

Yes, the scripts I'm looking at do it.



Don't fall into the same bad habits though! It's easier to prevent a habit than break one later.


The problem I'm having you didn't really touch on however, although I appreciate the long explanation :)

The news script I'm using says use;

$view_cat="All Oi News"; @include "news/news.php";

I can only assume this is to detect which category of news it's to display from news/news.php. $fp_news is the variable I would like to use to include the news into my page.

I think it will be easier if I just add $view_cat='All Oi News'; to my news/news.php file :)

I kind of touched on that, but without a more thorough explanation of the problem and understanding what $view_cat and $fp_news are it was hard to say.

If you have a php file that defines viewcat and fp_news and those variables are used by the file that you're including in that page, there shouldn't be any difference between you doing it the way you have, and adding those variables to the top of your news.php page itself.

My guess is that you've got the path or filename of the news page wrong (did you check the case, and the path exactly? Is it placed in a 'news' subfolder relative to the script that you're including it from? Is the page you are including it from being included in another page that you are executing and if so, is the relative path from that page to news.php correct?).

That's why I was suggesting that you remove the @ symbol. If you have the @ symbol there I think it'll surpress warnings that might otherwise appear (such as 'couldn't find new/news.php') which might help you to work out what's going wrong.

Is the content of the news.php page being displayed at all (if it isn't then there's a good possibility it isn't finding it from the script you're including it in).

If the news script content is being displayed (when you execute the page where you include it), is it displaying an error message? Or if it isn't displaying an error message and is returning unexpected results, what are they?

Pauly
November 23rd, 2004, 10:26
OK, removing the @ displays 'All Oi News' instead of the news. The files etc. are in the right place, and including it using the original script without a variable displays the news. I'm at a loss why it does this ....

ethicaldesign
November 23rd, 2004, 10:31
Can you post the news script that you're using? It would be easier for me to make sense of this if I could see the script itself and what it's doing with the variables you're defining before including it.

I can't see why it would just echoing your variable setting like that, unless it's something that it does for debugging purposes when the variable isn't set the way it's expecting it to be.

ethicaldesign
November 23rd, 2004, 10:32
P.S. The reason it might be displaying the news without a variable being set is that it might be the default condition (i.e. if you don't supply a category that you want it to display with the variables you're setting, it'll assume that you want to display the news from all categories - is that what happens when you don't specify a variable? You get news from all categories?)

Pauly
November 23rd, 2004, 10:40
is that what happens when you don't specify a variable? You get news from all categories?

It's supposed to, but it doesn't lol. The script is a bit screwed up. The page it includes is here(won't let me attach);

[syntax:66a0a4ffff="php"]
<html>
<head><title>JNews 5.0</title></head>
<body>
<?PHP
/************************************************** **********************/
/* JNews 5.0 */
/* ========= */
/* */
/* Copyright (c) 2004 by RJScriptz */
/* Website: NO FREE LINK */
/* Email: joonas@*******.com */
/* */
/* JNews is a free program that may be modified for private use */
/* freely with correct credit to the author(s). */
/* A Commercial license may be purchased by special request by email. */
/************************************************** **********************/

if (file_exists("jnews5/config.php")){include "jnews5/config.php";} else {include "config.php";}

if ($view_cat==""){$view_cat=$default;}

//Connect to MySQL
mysql_connect($host, $dbuser, $dbpass) or die( "Could not connect : " . mysql_error());
mysql_select_db($database) or die("Could not select database...");

function smiles($str){

$smile[0] = '$arrow'; $surl[0] = "<img src='news/smilies/arrow.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[1] = '$badgrin'; $surl[1] = "<img src='news/smilies/badgrin.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[2] = '$biggrin'; $surl[2] = "<img src='news/smilies/biggrin.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[3] = '$confused'; $surl[3] = "<img src='news/smilies/confused.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[4] = '$cool'; $surl[4] = "<img src='news/smilies/cool.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[5] = '$cry'; $surl[5] = "<img src='news/smilies/cry.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[6] = '$doubt'; $surl[6] = "<img src='news/smilies/doubt.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[7] = '$evil'; $surl[7] = "<img src='news/smilies/evil.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[8] = '$exclaim'; $surl[8] = "<img src='news/smilies/exclaim.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[9] = '$idea'; $surl[9] = "<img src='news/smilies/idea.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[10] = '$lol'; $surl[10] = "<img src='news/smilies/lol.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[11] = '$mad'; $surl[11] = "<img src='news/smilies/mad.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[12] = '$neutral'; $surl[12] = "<img src='news/smilies/neutral.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[13] = '$question'; $surl[13] = "<img src='news/smilies/question.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[14] = '$razz'; $surl[14] = "<img src='news/smilies/razz.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[15] = '$redface'; $surl[15] = "<img src='news/smilies/redface.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[16] = '$rolleyes'; $surl[16] = "<img src='news/smilies/rolleyes.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[17] = '$sad'; $surl[17] = "<img src='news/smilies/sad.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[18] = '$shock'; $surl[18] = "<img src='news/smilies/shock.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[19] = '$smile'; $surl[19] = "<img src='news/smilies/smile.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[20] = '$surprised'; $surl[20] = "<img src='news/smilies/surprised.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";
$smile[21] = '$wink'; $surl[21] = "<img src='news/smilies/wink.gif' alt=\"Oi Smiley\" title=\"Oi Smiley\">";

$c=count($smile);
for($i=0;$i<$c;$i++) $str=str_replace($smile[$i], $surl[$i], $str);
return $str;
}

//Loop all the news posts in the category in order by date
$query = "SELECT * FROM jnews5_posts WHERE category='$view_cat' ORDER BY `exactdate` DESC LIMIT 0 , $archive_number";
$result = mysql_query($query);
$i=0;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$i++;
$category=$line['category'];
$title=$line['title'];
$date=$line['date'];
$author=$line['author'];
$raw_post=$line['post'];

$post = smiles($raw_post);

include "$template";
echo "<br>";

}
////////////////////////////
// || || || //
// || || || //
// || || || //
// || || |||| //
// ||||||| || //
////////////////////////////
?>
</body>
</html>
[/syntax:66a0a4ffff]

ethicaldesign
November 23rd, 2004, 10:43
When I click that link it just takes me to the news.php file and tries to execute it (because it's on your server so is being run). I can't actually see the code. I'd need the file itself or for you to post the source code here.

When I click that link I don't get any output at all though, just a blank screen and 'done' in my status bar.

I'll pm you my email address so you can forward it to me if you like.

ethicaldesign
November 23rd, 2004, 10:43
LOL!. You beat me to it and posted it. Hang on a minute!

Pauly
November 23rd, 2004, 10:44
lol yea :) I noticed I couldn't see the source either ;)

ethicaldesign
November 23rd, 2004, 11:09
if ($view_cat==""){$view_cat=$default;}

This line indicates that there's a variable called $default defined in the config.php file (because it isn't defined anywhere in this script itself)

So I'm guessing that if you don't specify $view_cat at all, it'll display that default category specified in that config file. I would check inside that config.php file and see what $default is defined as.

My guess is that it'll be an ID number or something like that rather than a text description (particularly one with spaces in).

I think your original instructions for installing the script to use

$view_cat="All Oi News";

might just be a pointer indicating that the text 'All Oi News' should be replaced by the category ID that you want it to display. Without seeing the contents/structure of the database it's hard to be sure.

What is $default set as in the config.php file?

What sort of information does the field 'category' typically contain in your database itself?

There doesn't appear to be any check for that string 'All Oi News', in the news script itself, so if you don't have in your database table jnews5_posts a record with the category 'All Oi News' then it won't find any records when it queries the database.

Another thing to check is that the paths inside your news.php file specified here:

if (file_exists("jnews5/config.php")){include "jnews5/config.php";} else {include "config.php";}

are correct relative to the page that you're including it in.

If for example you have renamed the jnews5 folder to 'news' then you'll need to do the same in the news script itself.

Either that or make sure that config.php does exist in either a jnews5/ folder.

Or that it exists in the same folder that you have your file that's including the news.php file in (not the news/ folder itself).

You see, when you include 'news/news.php' in the page that you are executing, if there's an attempt to include the file 'config.php' without a path in the news.php script itself (this happens if it isn't found in the jnews5/ folder as per the above code snippet), it won't look in the news folder, but in the folder of the file that you're including the news.php file in in the first place.

Does that make sense? Not sure I'm explaining that well.

For example,

If you have a file mypage.php in the root folder. You include the file 'news/news.php' in that file.

The news/news.php file itself includes another file 'config.php' without any path info (as it does here if it doesn't find it in a folder called jnews5)

Then it won't look for 'news/config.php', but will look instead for '/news.php' because that is relative to the page mypage.php which is what's being executed.

Still not sure I'm explaining that very well. Hopefully it will make sense. If it doesn't let me know and I'll try to clarify it.

ethicaldesign
November 23rd, 2004, 11:21
P.S. No offense to the original authors, but if that category field contains textual information, this isn't a very well written script and will waste db space.

If you want to build a category based news system it's far better to have a seperate categories table with numeric IDs that are related to a seperate news items table through those IDs.

I won't ramble on about this because I've probably confused you enough with my explanation of relative paths, but if it's structured the way I think it might be, and the site you're putting it on is likely to store a lot of news articles, you might want to look for a better script written by someone who understands how relational databases work (could be wrong, not having seen the whole system but that's the impression I'm getting if that 'All Oi News' category is actually for real rather than just a general instruction to replace that text with a category identifier.

Pauly
November 23rd, 2004, 12:16
might just be a pointer indicating that the text 'All Oi News' should be replaced by the category ID

No, I put that in as instructed :)

you might want to look for a better script

I think I'll take your advice, I want something that will work without all this hassle. Thanks for your help :)

ethicaldesign
November 23rd, 2004, 12:31
might just be a pointer indicating that the text 'All Oi News' should be replaced by the category ID

No, I put that in as instructed :)


Yes, I understand, but perhaps you are misreading their instructions (maybe through no fault of your own if they just haven't documented it properly).

If you can have a look in the database and post a few records from that table showing what 'category' contains it might be the case that you're simply searching for a category that doesn't exist in the database itself?

I think I'll take your advice, I want something that will work without all this hassle. Thanks for your help :)

Are you on a tight timescale for this? Have you thought about writing your own? A news script would be a good exercise for learning php and about relational database structures. I can give you a hand with that if you want (at least point you in the right direction). Due to my workload at the moment progress would likely be quite slow though because I've got tons of other stuff on at the moment (fortunately or unfortunately depending how you tends to look at it).

Pauly
November 23rd, 2004, 14:18
.. tight timescale for this?

Pretty much. I have so much to do, and my whole database just screwed up, and now even though permissions are set to allow it says I don't have permission to view certain pages :( Aghhhh

ethicaldesign
November 23rd, 2004, 14:55
.. tight timescale for this?

Pretty much. I have so much to do, and my whole database just screwed up, and now even though permissions are set to allow it says I don't have permission to view certain pages :( Aghhhh

Man, I really feel for you. I know just how it is. I started work at 12ish last night and I'm still sitting here 14 hours later with another 4 or 5 hours stuff to do before I pack up (and still I'm a little behind). I'm just waiting for something to go wrong now myself :D

Hope you get the permissions thing sorted out anyway. What's the permissions error you're getting?

Pauly
November 23rd, 2004, 16:41
It was within vB saying I didn't have permission to view although I did, sorted it now, but now it can't find the forum id's lol, the database is screwed completely, unsure why because I haven't changed anything in it.

You should get sleep before you screw things up ;)

ethicaldesign
November 23rd, 2004, 17:10
It was within vB saying I didn't have permission to view although I did, sorted it now, but now it can't find the forum id's lol, the database is screwed completely, unsure why because I haven't changed anything in it.

:( - I hope that works out OK and you had a db backup!


You should get sleep before you screw things up ;)

Yep, just about to pack up. Just waiting for an email from someone to check that there's not a quick change I need to make to something before I go, then I'm off to watch a film and get some sleep :D

Pauly
November 23rd, 2004, 17:56
I found the problem, it seems the forumdisplay.php generates an error if I use this code;

[syntax:fcde2c3772="php"]// BELOW INCLUDES THE LATEST FORUM POSTS
ob_start();
require("inc/lastposts.php");
$lastposts = ob_get_contents();
ob_end_clean();

// BELOW INCLUDES AND DEFINES THE MENU
ob_start();
require("inc/nav.inc");
$top_menu = ob_get_contents();
ob_end_clean();[/syntax:fcde2c3772]

Was because the latestposts.php was pulling posts that didn't exist ;)

ethicaldesign
November 23rd, 2004, 18:09
What's the error that it generates (a cut/paste of it would be best)?

I can't see anything wrong with the code (apart from my usual gripe about the double quotes :) - bear in mind I'm tired now so probably not on top form though so I may be missing something - I'm not that familiar with output buffering in that way so that could be the case)

If you could post the error message itself it might help though (just be quick before I nodd off!).

Marble
November 26th, 2004, 08:40
I read something over at w3schools but I'm doing this with vB too, what I really would like to do is this;


$pageimg =
IF page=gallery.php SHOW <img src="images/misc/gallery.gif" />
OR
IF page=cars.php SHOW <img src="images/misc/car.gif" />


But obviously it's not that simple.

Jumping into part of an ongoing thread is dangerous I know, but to answer this question:

switch(basename($_SERVER['PHP_SELF'])) {
case 'gallery.php':
echo '';
break;
....etc....
}


also using single quotes versus double quotes in php really only comes down to this (in my experience):


$i = "42";
$var = "The meaning of life is $i";
--or--
$var = 'The meaning of life is '.$i.'';


Both are correct. In cases where you are echoing lots of html, eg., using single quotes is less messy. But if you are using variables in strings using double quotes is cleaner as it lets you use them directly without concatenation.

ethicaldesign
November 26th, 2004, 09:30
also using single quotes versus double quotes in php really only comes down to this (in my experience):


$i = "42";
$var = "The meaning of life is $i";
--or--
$var = 'The meaning of life is '.$i.'';


Both are correct. In cases where you are echoing lots of html, eg., using single quotes is less messy. But if you are using variables in strings using double quotes is cleaner as it lets you use them directly without concatenation.

Both will work but I wouldn't say both are correct (particularly if you take best coding practices into considerarion).

While you mightn't notice the difference in a small simple script, you will start to notice speed differences in larger more complex scripts, particularly where iteration is happening if you don't pay this issue the attention it deserves.

In your example above, assuming $i is meant to be a numeric value, it should properly be defined as :

$i=42;

Not only will that parse faster, but it'll allow the type to be checked (if required) later. This is one of the criticisms I regularly see leveled against php (that it isn't a strongly typed language). It can be used as a strongly typed language if we do things right, but it gives a lot of flexibility to allow people to do things wrong.

In a language like Java or C if you defined that variable in that way (as a string) and tried to use it as an integer later on in your script it would throw up a type error. PHP will let you get away with it that's all.

If $i was meant to be a string then defining it like you have (below) is wasteful and unncessary:

$i="42";

It should properly be written in single quotes.

There's no need to interpolate that string at all because it doesn't contain any variables. This is what the double quotes are intended for. Using them to define $i in this way (at least as far as your example above goes) is a misuse of that facility (again, it'll let you get away with it but that doesn't mean that it's right).

see: http://www.php9.com/index.php?p=4

which covers this

and :

http://www.phpbuilder.com/columns/tim20010101.php3?page=1 (this covers a few other areas - page 3 or 4 covers string handling I think).

Many professional programmers looking at your example would view that as sloppy programming (even if it the source code might read a bit nicer).

Don't take this the wrong way because there are undoubtedly areas of my own code (as there are in a lot of code out there) that could be improved aswell. Just trying to point this out to paul because I know he's just starting with php and it's much easier to get into the right habits from the start than to try to break bad habits later (using double quotes when they aren't required is a bad habit imho - and in most cases where you could reasonably use them single quotes will execute faster anyway).

If you need to output lots of html sometimes the best way to do that is by switching out of php mode altogether (this will apparently run faster and it will be even more readable).

Pauly
November 26th, 2004, 13:03
using double quotes when they aren't required is a bad habit imho - and in most cases where you could reasonably use them single quotes will execute faster anyway

Where would double quotes be mandatory? I know that when you "open" (not sure of its correct term) code for HTML using single you can use double within the HTML, also when opening with double I would have to use \" for the HTML to work correctly. But I'm not sure that I understand the whole when to use single or double quotes ......

If you need to output lots of html sometimes the best way to do that is by switching out of php mode altogether (this will apparently run faster and it will be even more readable).

I've been doing that ;)

ethicaldesign
November 26th, 2004, 13:19
Where would double quotes be mandatory? I know that when you "open" (not sure of its correct term) code for HTML using single you can use double within the HTML, also when opening with double I would have to use \" for the HTML to work correctly. But I'm not sure that I understand the whole when to use single or double quotes ......

There isn't really anywhere that I can think of where double quotes are mandatory. It's just a matter of convenience. If you read those links above it'll explain the issue properly and in detail.

About the only place I use double quotes myself are for SQL queries (where I know there are likely to be single quotes and several variable names required and they're unlikely to exist within an itteration). In some cases I don't use them in that context either (depending on the query).

The only time you should even consider using double quotes in my mind is when you need to include variables and/or control characters in the string you're defining or outputting (that's what the double quotes are intended for - though in most cases that can be done better with concatenation as far as I can tell as it'll tend to execute faster).

when you include double quotes within a single quote, like for example:

$textstring='This is some "text" here';

The double quotes are just treat like normal characters. So when you echo $textstring you'll get:

This is some "text" here.

No evaluation takes place inside the double quotes in that case because they're inside single quotes.

If you do:

echo "this is some text blah..blah..blahh";

the php interpreter will see the double quotes, evaluate the string looking for variable names and control characters then output the result.

if you do:

echo 'this is some text...blah..blah..';

it'll won't do the extra step of evaluating the string needlessly (as it contains no control characters or variable names) and will just output the string.

This doesn't seem like a big deal, and it probably isn't for small simple scripts, but imagine that you were sorting through an array or doing some other form of loop that might run a few thousand times before producing results. The little savings from using the single quotes add up.

If you need to output lots of html sometimes the best way to do that is by switching out of php mode altogether (this will apparently run faster and it will be even more readable).

I've been doing that ;)

Another cool way of doing that is using heredoc formatting (I think there's something mentioned about that on one of those links but if not if you do a search for it you'll find stuff. I don't tend to use this myself though and I'm not sure of the advantages (perhaps it's even faster than moving in and out of php mode).

sonicgroup
November 26th, 2004, 14:15
The only advantage I've found to using heredoc is that it works similar to enclosing the whole shebang in double quotes - i.e. you can throw variables in there without escaping or concatenating anything.

The downside to heredoc, and the main reason I don't use it, is that it screws up my editor's syntax highlighting. :o