• 0

PHP: Do you know basic syntax?


PHP: Do you know basic syntax?  

89 members have voted

  1. 1. Do you know basic syntax?

    • Yes, I'm a professional developer.
      33
    • Yes, I'm not a professional developer.
      30
    • I thought I did until now.
      13
    • No.
      13


Question

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";

https://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:

https://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:

https://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:

https://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:

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

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

https://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++ ) {}

https://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.

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

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

Edited by balupton
Link to comment
https://www.neowin.net/forum/topic/531433-php-do-you-know-basic-syntax/
Share on other sites

Recommended Posts

  • 0

I always check my vars, and also use the proper php tag. Don't use single quotes though, never learned it that way. Btw, how much processing time could it cost really? A ms isn't really valuable to me, especially not in non-professional environments.

Thanks for the tips though. :)

  • 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 < 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 < $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 = & $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.

  • 0
  balupton said:
for ( $i = 0; $i < 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 < $n; $i++ ) {}

[s]Wouldn't that do the exact same thing, as it still has to assign $n? I don't use for() much though, so I'm not 100%.[/s]

noob. Just realised.

Edited by TurboTuna
  • 0

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

// however
for ( $i = 0, $n = sizeof($array); $i &lt; $n; $i++ ) {}
// is the same as
$i = 0;
$n = sizeof($array);
for ( , $i &lt; $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.

  • 0

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 &lt; 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.

  • 0

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.

  • 0
  balupton said:
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.

  • 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.

  • 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']) &amp;&amp; $_GET['param'] )
// or
if ( !empty($_GET['param'] )

Neither of those will return notices.

  Quote
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';

  Quote
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.
  • 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.

  • 0

phpmozzer thanks for that tip, didn't know it myself :) Here's the reasoning behind why that is for people wanting to know:

  Quote
2) When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

Taken from: http://ilia.ws/archives/12-PHP-Optimization-Tricks.html

Some others that may be worth mentioning:

echo is faster than print. Reference: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

isset($array[$key]) is faster than array_key_exists($key, $array), but array_key_exists should be used if you want to respect empty (NULL) values inside the array. Reference: http://php.net/array_key_exists

  • 0

I always turn all errors on. None of my apps ever have any warnings or notices.

I exclusively use object oriented programming in PHP. Always found it to be a time saver and makes code smaller since I reuse object left and right.

A lot of people don't have a programming background and PHP is their first language. PHP is very forgiving (really!) as far as a programming language goes. People make mistakes and the PHP engine keeps on ticking.

Also, people have no concept of speed or memory allocation. It doesn't really matter on small projects but once you go corporate where there are hundreds of hits a minute, your app better be optimized to the fullest.

Here are some tips on speed... PHP speed, fastest to slowest:

for ()

foreach ()

while()

do {} while()

for() is the fastest for obvious reasons, the loop is doing a numerical operation, which, computers were designed for in the first place, no arrays, true/false, return values, just pure math.

foreach() is secondary for a less obvious reason. While it is slower then for(), since an actual iteration occurs, it's faster than while() because no return value is required.

do-while() is obviously going to be the slowest. It inherits the requirements of while() which is just above it in speed, and requires PHP to interpret a second construct "do".

Also, on control structures, switch is faster then if/else nests.

It's easy to understand why. Here's an example:

if ($variable === true)
	{
		// do something
	} elseif ($variable === false)
		// do something else
	}

In this example, PHP has to read each statement separately. So PHP will read "$variable === true" then "$variable === false". It has to process both those statements.

Here's the same as a switch:

switch ($variable)
	{
		case 'true':
			// do something
			break;
		case 'false':
			// do something else
			break;
	}

Now PHP will read "$variable === true OR false". Since PHP is only working with one variable, it doesn't have to parse the statement twice.

  • 0

Thanks for mentioning that stuff redFX :)

Just to note, that the different loops do all serve different purposes as well:

do whiles should be used for at least one iteration, saves you duplicating code up the top of your while loop.

foreach loops make a copy of the array in question, you do not work with it directly.

One that i'm quite curious about is using loose comparison over strict, eg. $var1 == $var2 or $var1 === $var2, which one is faster?

  • 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.

  balupton said:
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.

  • 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 &amp;&amp; gettype($var) == gettype(false)

....

  • 0
  balupton said:
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 &amp;&amp; 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.

Edited by redFX
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • ...so more bloat is added (that naturally is always running in the background, using resources) that will report that you have a lot of bloat (and also a few more ads were also added but that has nothing to do with anything, right...).
    • Thank you for replying! Is MP600 also good? Where I'm looking they don't have MP700. I was also looking at Corsair T500, that comes with heatsink.
    • As someone who was born in 1980, I’m feeling this.
    • Amazon Deal: This Vifa Stockholm 2.0 is one of the best sounding bluetooth speakers by Sayan Sen A few days back we covered some great JBL bluetooth speaker deals across several of its popular models. The discounts are still live and you can check them out in this dedicated piece. Meanwhile for those who prefer more powerful home cinema sound systems, Nakamichi and Samsung are offering the Dragon and Shockwafe models, and the Q-series models, respectively, at their best ever prices. However, if you are someone who is looking for a bit of both, the portability of a bluetooth speaker and the fidelity of a good sounding hi-fi system then the Vifa Stockholm 2.0 Bluetooth Soundbar is something you should look at as it's currently a nice deal (purchase link under the specs table below). While you are not getting a subwoofer with the Vifa Stockholm as it is a 2.0 system, Vifa promises lows down to 42 Hz at +3dB and that should be pretty good for a device lacking a dedicated bass unit; it does pack passive radiators to help with the bass. The Stockholm 2.0 is praised for its sound quality (SQ) and one of the reasons behind it is becasue it has three-way drivers. The technical specifications of the Vifa Stockholm 2.0 Bluetooth Soundbar are given below: Specification Frequency Response 42 Hz – 20 kHz @ ±3 dB Materials Frame: One-piece die-cast aluminium; Enclosure: ABS reinforced; Grills: Kvadrat textile Connectivity Bluetooth® Qualcomm aptX™ HD audio; Wi-Fi Direct & networked (2.4 GHz); Wired optical or analog (3.5 mm mini-jack); USB-disk; Vifa®HOME, Vifa®LINK, Vifa®PLAY Driver Units Tweeter: 2 × 28 mm soft-dome drivers; Midrange: 2 × 80 mm aluminium-cone drivers; Woofer: 4 × 100 mm flat sandwich-cone drivers (force-balanced, backed by 4 passive radiators) Other Features Apple AirPlay & DLNA streaming; DSP signal processing; 6-channel high-performance power amplifier Get it at the link below: Vifa Stockholm 2.0 Bluetooth Soundbar, Nordic Design Soundbar, Smart APP Multi-Room System (Slate Black): $1156.99 (Sold and Shipped by Amazon US) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Explzh 9.81 by Razvan Serea Explzh is a free Windows archive manager for creating, extracting and managing archives. The program supports many different types of archives, including zip, 7z, rar, tar, ace, lzh, arj, cab, iso, img, msi, sfx and more. Apart from archive creation and extraction, you will also be able to verify compressed data for errors, initiate repair routines, split data into multiple items, and more. It additionally allows you to password protect your data and attach digital signatures to files. Key features of Explzh: Explorer-like GUI and operability. LHA, ZIP (ZIPX), JAR, CAB, RAR, TAR, TAR.XXX, 7z, ARJ, WIM, CHM, PE, HFS, NSIS Format Installer, ISO, InstallShield, MSI, and several other formats... Support for more archive formats by introducing the integrated archiver DLL. Self-extracting archive creation function that can create high-performance automatic installers. Digital signature addition function to created self-extracting archive. Office 2007 or later document compression / image optimization re-archiving function. Supports compression and decompression of Unicode file names. Supports compression and expansion exceeding 4GB. AES encryption function. You can create a robust secure ZIP encryption archive. Thumbnail function of image file. In-library file search function. . Equipped with archive file conversion function. File split function. The split file has a self-consolidation function, and can concatenate files larger than 4GB. (No need for batch file or connection software) UU (XX) Encode, Base64 decode function. FTP upload function Supports Windows 11 shell integration extended context menu. Explzh 9.81 changelog: Improved to send update notifications to the shell when making changes such as additional compression to existing zip and 7-zip files. This also updates the Explorer view of the open file in real time. (If the drop target feature is enabled, you can easily create an encrypted ZIP by dragging and dropping onto the ZIP icon while holding down the Ctrl key.) When the zip drop target setting is enabled, the "Compressed (zipped) Folder" item will be added to the "New" shell context menu if it does not already exist. Password manager bug fix: Fixed a bug that caused the app to crash when reading password.dat (password data) when changing authentication method. Updated to Visual Studio 2022 v.17.14.9. Download: Explzh 64-bit | Explzh 32-bit | ~6.0 MB (Freeware) Download: Explzh ARM64 | 5.9 MB View: Explzh Home Page | Screenshot | Themes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Snake Doc earned a badge
      Week One Done
    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
    • Week One Done
      Sender88 earned a badge
      Week One Done
    • Dedicated
      Daniel Pinto earned a badge
      Dedicated
    • Explorer
      DougQuaid went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      611
    2. 2
      Michael Scrip
      199
    3. 3
      ATLien_0
      190
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      125
  • Tell a friend

    Love Neowin? Tell a friend!