• 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

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

:)

  • 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

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

  • 0

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

$T->start();

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

$T->stop();

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

$T->start();

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

$T->stop();

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

Gives

If Else Comparison:

0.00028000s

Ternary Comparison:

0.00024100s

  • 0

1. true == true Took 3

2. true === true Took 2

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

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

Output comes from

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

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

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

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

  • 0

Hrmm, using

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

$T->start();
ob_start();

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

ob_end_clean();
$T->stop();

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

$T->start();
ob_start();

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

ob_end_clean();
$T->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

Edited by balupton
  • 0

phpmozzer, i did the benchmarks for loose vs strict here:

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

strict are faster.

I've updated the first post of this topic to include all the tips we've found so far :)

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

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

  • 0

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... ;)

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

    • No registered users viewing this page.
  • Posts

    • Same, never saw it on Android or iOS. Guess only some people got it *shrugs*
    • Anthropic pulls Fable 5 and Mythos 5 after US export control order by Pradeep Viswanathan In April this year, Anthropic launched the Claude Mythos Preview frontier model with state-of-the-art cyber and coding capabilities for a select set of companies around the world. After preparing appropriate guardrails, early this week, Anthropic launched Claude Fable 5 and Mythos 5, its most capable AI models. Claude Fable 5 is for general users and comes with strict safeguards, while Mythos 5 is designed with fewer safeguards for cybersecurity and biology use cases. Today, Anthropic abruptly suspended access to its Fable 5 and Mythos 5 AI models for all customers after receiving an export control directive from the US government. The company received the directive from the government today at 5:21 p.m. ET, and the received letter did not provide any details regarding the national security concern. Anthropic understands that the government became aware of a method to bypass, or “jailbreak,” Fable 5, which might be the reason behind the directive. The order was issued under national security authorities and requires the company to suspend all access to Fable 5 and Mythos 5 by any foreign national, whether they are inside or outside the United States. The restriction also applies to foreign national employees working at Anthropic. As a result, the company has disabled both models for all customers to ensure compliance. Access to previous Anthropic models like Opus and Sonnet is not affected by this government order. The company highlighted that it had developed strong safeguards to reduce the possibility that Fable is misused for tasks related to cybersecurity. In fact, many developers are complaining that the safeguards are going overboard. Additionally, the company worked with the US government, the UK AISI, multiple private third-party organizations, and internal teams to red-team Fable’s safeguards for thousands of hours. Finally, Anthropic noted that no testers have yet been able to find a universal jailbreak on Fable 5. As expected, Anthropic disagrees that a narrow potential jailbreak should lead to the recall of a commercial model used by hundreds of millions of people. It warned that applying this standard across the AI industry could effectively halt new frontier model deployments. Anthropic concluded by mentioning that it is working to restore access to Fable 5 and Mythos 5 as soon as possible and plans to share more details within the next 24 hours.
    • Brave Browser 1.91.172 is out.
    • Any Video Converter Free 9.2.3 by Razvan Serea Any Video Converter is an All-in-One video converting tool with an easy-to-use graphical interface, fast converting speed and excellent video quality. Any Video Converter supports all popular video formats and converts your videos to different video formats including MP4, MOV, MKV, M2TS, M4V, MPEG, AVI, WMV, ASF, OGV, WEBM, and more. It supports converting videos to customized percent (50%, 100%, 200%, and more) or resolution (480p, 720p, 1080p, 4K, and more); It supports encoding videos into x264, x265, h263p, xvid, mpeg, wmv, and more. Any Video Converter Free key features: Compatible with Windows 11/10/8.1/8/7 (32-64bit) User interface are available in 14 languages Convert all kinds of video formats including high-definition videos Extract audio from any videos and save as MP3/WMA for your mp3 player Take snapshot from any videos and build your own picture collection Support high-definition for both input and output Batch add videos from hard drive and batch convert Customize output parameters completely as you like Manage your output videos files by group or output profile Merge several video files into a single and long one Clip a video into segments Free Audio Filter: Adjust audio volume and add audio effects Crop frame size to remove black bars and retain what you want only Adjust the brightness, contrast, saturation Rotate or flip or add noise/sharpen effects Produce output video with subtitles of your own dialogue and much, much more... Any Video Converter Free 9.2.3 changelog: Fixed video download engine auto-update failures. Added custom speed control support in the speed change tool. Added support for downloading YouTube AI-generated subtitles. Added support for preserving original audio stream in the format convert tool (e.g., Dolby Atmos, DTS:X). Fixed other bugs and improved overall performance. Download: Any Video Converter Free 9.2.3 | 7.6 MB (Freeware) View: Any Video Converter Free Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
    • Rookie
      Rimplesnort went up a rank
      Rookie
    • One Year In
      Markus94287 earned a badge
      One Year In
    • One Month Later
      Markus94287 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      503
    2. 2
      +Edouard
      176
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      92
    5. 5
      Steven P.
      79
  • Tell a friend

    Love Neowin? Tell a friend!