• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

Archived

This topic is now archived and is closed to further replies.

  • 0

PHP: Do you know basic syntax?

PHP: Do you know basic syntax?  

89 members have voted

You do not have permission to vote in this poll, or see the poll results. Please sign in or register to vote in this poll.

Question

balupton    0

It seems that a lot or even most php programmers just jumped in and never read the manual or even know basic syntax...

The ones I see all the time are:

Not checking variable existence by just doing

$param = $_GET['param'];

instead of the correct

$param = isset($_GET['param']) ? $_GET['param'] : NULL;

which will not return a notice exception

Reference: http://au3.php.net/manual/en/language.variables.php

Using short tags

<?

instead of the proper

<?php

which will run on many more servers

Reference: http://php.net/manual/en/language.basic-syntax.php

Also the misuse of double quotes

$var = "hello";

should be

$var = 'hello';

which saves processing time

Reference: http://php.net/manual/en/language.types.st...g.syntax.single

Those are just some of the most common ones.

So what i'm asking is:

Why didn't you know this stuff if you didn't before hand?

Or if you did know this, then why do you think things like this are so ignored?

Note:

The option "I thought I did until now." should read "No, I'm a professional developer."

The option "No." should read "No, I'm a unprofessional developer."

-------------------

This thread has kinda turned into a tips thread, so here are a collection of tips that have been collected so far.

Single quotes vs Double quotes

$var = 'hello';
$string = '$var is '.$var;
// is faster than
$var = 'hello';
$string = "\$var is $var";

http://www.neowin.net/forum/index.php?show...amp;p=588249172

Switch statements VS if then else statements

switch ($var)
{
   case $option1:
	  break;
   case $option2:
	  break;
   default:
	  break;
}
// is faster than
if ( $var == $option1 )
{ }
elseif ( $var == $option2 )
{ }
else
{ }

Thanks to redFX for reminding us of that:

http://www.neowin.net/forum/index.php?show...amp;p=588271991

If then else statements VS ternary statements

if ( false )
{ echo 'true'; }
else
{ echo 'false'; }
// if faster than
echo (false ? 'true' : 'false');
// which is faster than
echo false ? 'true' : 'false';

Also applies for $var =, instead of echo. Thanks to redFX for that:

http://www.neowin.net/forum/index.php?show...amp;p=588271991

Pre-Increment VS Post-Increment

++$i;
// is faster than
$i++;

This applies everywhere, so in for loops etc. Thanks to phpmozzer for that:

http://www.neowin.net/forum/index.php?show...amp;p=588271806

Loops in order of speed

for, foreach, while, do-while. Thanks to redFX for that:

http://www.neowin.net/forum/index.php?show...amp;p=588271808

Strict (===) comparison is faster than loose (==) comparison.

http://www.neowin.net/forum/index.php?show...amp;p=588271983

Instantiating classes

$Class = & new Class();
// is faster than
$Class = new Class();

Thanks to http://www.php.lt/benchmark/phpbench.php

For loops and size calculations

for ( $i = 0, $n = sizeof($array); $i < $n; $i++ ) {}
// is faster than
for ( $i = 0; $i < sizeof($array); $i++ ) {}

http://www.neowin.net/forum/index.php?show...amp;p=588249623

Variable declarations and memory

$var1 = 'hello';
$var2 = $var1; // In C the variable var2 is created in memory right here
$var2 = 'bye'; // In PHP the variable var2 is created in memory here, up until now it still uses the same location of memory as var1

So in general, references should only be used if you want to work with the original variable, as it does not save memory or processing time.

http://www.neowin.net/forum/index.php?show...amp;p=588249172

If you know any others, feel free to post them :)

Share this post


Link to post
Share on other sites

Recommended Posts

balupton    0
Variable declarations and memory

$var1 = 'hello';
 $var2 = $var1; // In C the variable var2 is created in memory right here
 $var2 = 'bye'; // In PHP the variable var2 is created in memory here, up until now it still uses the same location of memory as var1

So in general, references should only be used if you want to work with the original variable, as it does not save memory or processing time.

http://www.neowin.net/forum/index.php?show...amp;p=588249172

Regarding that, I've just run some benchmarks, and it seems that if say $var1 = $array['hello'], then references are faster! For both reading and setting!

Check out the last section of the attached php file for the benchmarks.

benchmarks.zip

Share this post


Link to post
Share on other sites
balupton    0

Ok the site http://www.php.lt/benchmark/phpbench.php says that === are quicker :) it's the last benchmark on the site. Good site, show's benchmarks for a lot of stuff discussed here :)

Share this post


Link to post
Share on other sites
balupton    0

for ( $i = 0; $i < sizeof($array); $i++ ) {}
// is the same as
for ( $i = 0; true; $i++ ) {
if ( !($i < sizeof($array)) ) break;
}

// however
for ( $i = 0, $n = sizeof($array); $i < $n; $i++ ) {}
// is the same as
$i = 0;
$n = sizeof($array);
for ( , $i < $n; $i++ ) {}

Make sense? In the first example we are re-calculating the size each time to use in the check, however in the 2nd example we calculate it once but we still check each time.

Share this post


Link to post
Share on other sites
Mathachew    149

Got some good pointers on here.

I create functions to check global variables so that the script doesn't crap out. Here's an example:

function Ses($key)
{
	if(array_key_exists($key, $_SESSION))
	{
		if(is_array($_SESSION[$key]))
			return $_SESSION[$key];
		else
			return trim($_SESSION[$key]);
	}
}

The same would apply to $_REQUEST and $_SERVER. It will even trim your values, just in case.

This is something I learned a few months ago from another developer here, which I love doing:

// For certain cases where a number needs to be preceded by a 0
$i = ($i < 10 ? '0'.$i : $i);

// Also useful for functions where the variable doesn't have to be passed
// Using Ses() from earlier example
function GetUserInfo($user_id = false)
{
	// Method 1
	if(!$user_id)
		$user_id = Ses('user_id');

	// Method 2, i likes!
	$user_id = ($user_id ? $user_id : Ses('user_id'));

	// blah blah
}

The second usage isn't necessary and I'm not certain if that increases server load, but given that it's such a small operation it shouldn't be much of a difference either way. It's not the best example of this feature, but I've found it to be very useful in other scenarios.

Share this post


Link to post
Share on other sites
redFX    0

The difference between == and === is that === checks not only value but type (float, bool, etc)

If you don't care about a variables type, use == which is faster.

Using === not only checks value but type so that's 2 things being processed rather then =='s 1 thing.

Ok the site http://www.php.lt/benchmark/phpbench.php says that === are quicker :) it's the last benchmark on the site. Good site, show's benchmarks for a lot of stuff discussed here :)

Something strange with the conclusion on that site. He says == takes 2 ms to process and === takes 3 ms. Then he says === is faster. He got his conclusion wrong based on his tests.

=== is slower then ==

And I just explained why.

Share this post


Link to post
Share on other sites
chavo    1

I am unprofessional developer. I downloaded a few free CMSs a couple of years ago to put up on my bands site. I ended up using e107. Then I started customizing it and sending in bug patches to the lone developer at the time. I eventually was asked to join a dev team. I look back now and realize how crappy some of that code was, but it worked and was a good time, and a great learning experience.

Share this post


Link to post
Share on other sites
balupton    0

Chavo, yeah that's the way to go, i started on b2evolution. Even now i look at code i did a few months ago and go dam that was bad.

Cailin, you could use;

if ( isset($_GET['param']) && $_GET['param'] )
// or
if ( !empty($_GET['param'] )

Neither of those will return notices.

Because of how PHP runs, the only values in PHP that are considered to be false are "false" (boolean value), 0 (integer), null, and the empty string.
On a unrelated note that you probably already know but i'll say it anyway for the people that don't know is that the above is only by loose comparison not strict. Eg.

$var = false === 0;
var_export($var); // will output 'false';
// however
$var = false == 0;
var_export($var); // will output 'true';

Of course this can only be really used if you TRUST what you are going to get in $_GET['blah']. It would always be a good idea to check any external variables with some function that will strip malicious text.
Sure sure, but you can never really trust what is coming in through any user input, as it's easy to modify get, post, and cookie values.

Share this post


Link to post
Share on other sites
+mrbester    164

Point of note: This thread isn't about syntax, which is purely how a block of code is structured (in other words, do you know how to write a "sentence" or "paragraph" in this language?), but refactoring.

Edit: The original post (first example) is an example of differences in variable aquisition: In ASP setting a variable to a (non-existent) querystring key's value results in a zero length string (the same as if the key did exist, but the value wasn't set), whereas in .NET and PHP it results in a NULL (or possibly even errors out), which is a different variable type.

ASP does not have an equivalent isset() function. You have to write one yourself... ;)

Share this post


Link to post
Share on other sites
Cailin    0

isset is almost ignorable in a lot of cases. For example:

if (isset($_GET['blah'])) ...

Will return true and perform the action if and only if the $_GET['blah'] variable is set. This however does some processing and determines if $_GET['blah'] really is true or false.

Much simpler is to just do...

if ($_GET['blah']) ...

Because of how PHP runs, the only values in PHP that are considered to be false are "false" (boolean value), 0 (integer), null, and the empty string. So if there isn't a value in $_GET['blah']... the if statement won't execute. This is quicker in a LOT of cases because you don't have to evaluate more than one if statement.

Of course this can only be really used if you TRUST what you are going to get in $_GET['blah']. It would always be a good idea to check any external variables with some function that will strip malicious text.

Edit: I realize that doing it the second way causes a warning to be raised. I also believe this can be ignored in almost all cases other than the case mentioned in the last paragraph.

Share this post


Link to post
Share on other sites
Quboid    0

Just as long as people use $_GET and not auto-globals. When I first used PHP4, I couldn't figure out why data wasn't being passed. Now, I'd never use the old automatic method even though I did checks in the code.

As regards "foo $bar foo" verus 'foo ' . $bar . ' foo', I would expect the first to be faster but this is incredibly close. I avoid using double quotes if there is no variable content but beyond that, readable code is more important than shaving a fraction of a millisecond off. In this case, I think the first option is both more readable and faster so it's not an issue here of course.

balupton - nice tips. I didn't know about the reference-to-constant-variable tip. I thought $foo = $bar would immediately copy $bar in memory into $foo's space so I would use a reference on the assumption that it just uses 8 bytes and minimal processing whereas without a reference, I thought the whole variable would be copied. Readability comes into this as well - if you use a reference, it's clear that you want to access the same memory, whereas without a reference, you could experience some head-scratching bugs later on if you do make changes to $foo and expect $bar to update. It's up to the individual coder where their priorities lie, just remember that developer time is a resource just like processor time and memory. Comments work wonders in this situation too.

Share this post


Link to post
Share on other sites
balupton    0

I would imagine, and that benchmark site agrees, that === is faster than == as === checks the value directly, however == takes into account variable types, eg. comparing the value against the other types as well. Eg. this is what i would imagine happens:

// $var == false looks like
$var === false || $var === '' || $var === 0
// where $var === false looks like
$var === false

Well that's what i would of thought, and makes sense to me, and seems to be right so far...

However what your saying is that

// $var === false looks like
$var == false && gettype($var) == gettype(false)

....

Share this post


Link to post
Share on other sites
primexx    372

Question: is it quicker to parse 'text '.$var.' more text' or "text $var moretext"?

Share this post


Link to post
Share on other sites
redFX    0
I would imagine, and that benchmark site agrees, that === is faster than == as === checks the value directly, however == takes into account variable types, eg. comparing the value against the other types as well. Eg. this is what i would imagine happens:

// $var == false looks like
$var === false || $var === '' || $var === 0
// where $var === false looks like
$var === false

Well that's what i would of thought, and makes sense to me, and seems to be right so far...

However what your saying is that

// $var === false looks like
$var == false && gettype($var) == gettype(false)

....

Yup, I'm saying the bottom code happens. Take a look at this example:

$test1 = (bool)1;
$test2 = (float)1;

if ($test1 == $test2) echo 'Yes'; else echo 'no';
echo "\n";
if ($test1 === $test2) echo 'Yes'; else echo 'no';

The first if statement using == outputs 'Yes'. It does a quick value comparison disregarding type. Whereas the second if statement does a value comparison plus gets the type for each value and compares that too. The output of the second if statement is 'No'

EDIT: Ok, strangely enough === seems faster then == in my tests. I ran an if statement 5 million times once each for == and for ===.

== seemed to be 4/10 of a second faster then === when processing 5 million times.

Its rather strange since == disregards type and === has to check type.

Alright, time to dig into the source code for PHP to see why that's the case.

Share this post


Link to post
Share on other sites
Mike    89
So what i'm asking is:

Why didn't you know this stuff if you didn't before hand?

Or if you did know this, then why do you think things like this are so ignored?

i pretty much always use isset, reason people dont? maybe they don't realise its needed? this isn't really syntax tho

<?php over <? is more for portability/compatibilty, i've always used <? as its shorter and works :p maybe if i did something that was going to be released to a large user base i may then use <?php

i tend to use double quotes due to coming from C and because i tend to put new lines characters in which dont work in single quotes

i wouldn't say anything you pointed out in the first post is basic syntax really, both ways for all things mentioned are valid basic syntax, just some are slower / less compatible.

Share this post


Link to post
Share on other sites
balupton    0

Primexx, yes using single quotes would be faster, as using double quotes would waste time processing normal text. I only ever use double quotes for new lines (but that's just me).

Code.Red, add error_reporting(E_ALL); to the start of your code, and then see how many notices you get, as doing if ( $_GET['param'] ) to check if variables exist will send out notices if they don't, so on servers that do have all error reporting enabled their page would be riddled with notices.

status-seeker, yeah only a few milliseconds, but it's just getting into the correct habit, like coding correct xhtml/css valid, or even unobtrusive javascript right from the start, so it doesn't bight you in the ass later.

Some other ones are:

for ( $i = 0; $i &lt; sizeof($array); $i++ ) {}
// the above has a serious performance problem, as it would re-calculate the size of the array in each iteration of the for loop

for ( $i = 0, $n = sizeof($array); $i &lt; $n; $i++ ) {}
// the above is what should be used, as it gets the size of the array once and only once

The above is applicable for most languages, some C compilers detect it and fixes it up.

Another is if you are not modifying a variable, do not make a reference of it. In C what programmers do if they are working with large variables if pass it by reference to avoid duplicating the variable in memory. PHP only duplicates the variable in memory if the variable is changed. For example

$var1 = 'hello';
$var2 = $var1; // In C the variable var2 is created in memory right here
$var2 = 'bye'; // In PHP the variable var2 is created in memory here, up until now it still uses the same location of memory as var1

This is useful when working with large arrays, as what some people do is the following

{   // inside the for loop
$var = &amp; $array[$i];
// some work with $var which doesn't modify it

So in this case it would be slower than the $var = $array[$i] alternative, as doing $var = & $array[$i] would create $var in memory and make it contain the address of $array[$i], however not using references it would just use $array[$i] directly until $var is modified.

If i remember any others i'll be sure to post them.

Share this post


Link to post
Share on other sites
balupton    0

Yeah still seems illogical to me... ;) I'm benchmarking it now to see what happens...

And instead of

if ($test1 == $test2) echo 'Yes'; else echo 'no';

you could use the better option of

echo $test1 == $test2 ? 'Yes' : 'no';

:)

Share this post


Link to post
Share on other sites
balupton    0

Yeah, my benchmarks agree :)

Dummy Test:

0.00022300s

For Loop (Post-Increment):

0.00023600s

For Loop (Pre-Increment):

0.00017100s

Loose Comparison:

0.00047200s

Strict Comparison:

0.00030000s

Each loop goes through 1000 iterations.

benchmarks.zip

Share this post


Link to post
Share on other sites
redFX    0
Yeah still seems illogical to me... ;) I'm benchmarking it now to see what happens...

And instead of

if ($test1 == $test2) echo 'Yes'; else echo 'no';

you could use the better option of

echo $test1 == $test2 ? 'Yes' : 'no';

:)

Ahh yes, here's a good tip... using the first one is faster then the second one.

I just ran a benchmark on them both and the first one (with the if statement) is a full second faster then the second one (when running them each 5 million times).

Share this post


Link to post
Share on other sites
phpmozzer    0

The one which most people miss and the professionals get is the ++$i; pre-incrementation which is much faster especially on large loops

Share this post


Link to post
Share on other sites
balupton    0

// ---------------------
// Test 5
echo "\r\n".'If Else Comparison: '."\r\n";

$T-&gt;start();

for ( $i = 0, $n = 1000; $i &lt; $n; ++$i )
{
	if ( false )
	{ true; }
	elseif ( true )
	{ false; }
}

$T-&gt;stop();

// ---------------------
// Test 6
echo 'Ternary Comparison: '."\r\n";

$T-&gt;start();

for ( $i = 0, $n = 1000; $i &lt; $n; ++$i )
{
	false ? true : false;
}

$T-&gt;stop();

// ---------------------

Gives

If Else Comparison:

0.00028000s

Ternary Comparison:

0.00024100s

Share this post


Link to post
Share on other sites
gigapixels    99

goto.png

:whistle:

Share this post


Link to post
Share on other sites
phpmozzer    0

1. true == true Took 3

2. true === true Took 2

3. 'Hello' == 'Hello' Took 5

4. 'Hello' === 'Hello' Took 2

Output comes from

&lt;?php
$loop = 10000000;
$time = time();
for ( $i = 1; $i &lt;=$loop; ++$i )
{
	if ( true == true ) 
	{ }
}
$end = time() - $time;
echo "1. true == true Took $end\n";

$time = time();
for ( $i = 1; $i &lt;=$loop; ++$i )
{
	if ( true === true )
	{}
}
$end = time() - $time;
echo "2. true === true Took $end\n";

$time = time();
for ( $i = 1; $i &lt;=$loop; ++$i )
{
	if ( 'Hello' == 'Hello' ) 
	{ }
}
$end = time() - $time;
echo "3. 'Hello' == 'Hello' Took $end\n";

$time = time();
for ( $i = 1; $i &lt;=$loop; ++$i )
{
	if ( 'Hello' === 'Hello' )
	{}
}
$end = time() - $time;
echo "4. 'Hello' === 'Hello' Took $end\n";
?&gt;

Share this post


Link to post
Share on other sites
balupton    0

Hrmm, using

// ---------------------
// Test 5
echo "\r\n".'If Else Comparison: '."\r\n";

$T-&gt;start();
ob_start();

for ( $i = 0, $n = 1000; $i &lt; $n; ++$i )
{
	if ( false )
	{ echo 'true'; }
	else
	{ echo 'false'; }
}

ob_end_clean();
$T-&gt;stop();

// ---------------------
// Test 6
echo 'Ternary Comparison: '."\r\n";

$T-&gt;start();
ob_start();

for ( $i = 0, $n = 1000; $i &lt; $n; ++$i )
{
	echo false ? 'true' : 'false';
}

ob_end_clean();
$T-&gt;stop();

// ---------------------

Gives

If Else Comparison:

0.00031100s

Ternary Comparison:

0.00041700s

Which is the opposite to what i posted above, seems that the echo makes a big difference.

Edit: Actually it is not the echo that cause the change, it was the use of strings, eg. echo 'true' instead of echo true. So thanks for that redFX :D

Share this post


Link to post
Share on other sites
Code.Red    5

The only thing I didn't do is checking variable existance, and that's because I've only ever seen it done just assigning it, and never had any problems with it.

I'd be interested in knowing some more if you know any.

Share this post


Link to post
Share on other sites
jimbo11883    1

There's some good tips in this thread for those who don't know about it... :)

Share this post


Link to post
Share on other sites

  • Recently Browsing   0 members

    No registered users viewing this page.