<?php
# some comment
?>
and
<?php
// some comment
?>
are used for single-line code commenting in PHP, and that former comes from shell scripting and // comes from C++.
However I am curious to know if there are any differences between using // and # for single line commenting and anyone has come across cases specific cases where one or other should not be used.
Only difference I could think of is there is one character in '#' and two in '//' so perhaps will there in larger scripts some small size and/or performance gains ??
For me it's easier to type // by double pressing the key on my keyboard moving just my right pinky one key down and pressing it two times.
If I want to do # I need to use both hands and the movements are "bigger" ;). It's the same for echo and print.
But in print and echo "scenario" you can hear an argument that one function is a little slower, however I am not sure right now which one ;) but it's really something that is no deal-breaker when optimizing for code I guess.
According to this topic echo is a little faster:
Should I use echo or print in php scripts?
Related
I need to find 1 word from a string, like:
$row['keyword'] = "hello my name is jon";
If the word "text" matches to one word from $row['keyword'] so do something..
I try this, but i think there is a better way:
foreach($rows as $row)
{
if (strpos($row['keyword'],"text") !== false) {
// do something
}
}
I think the code you've provided looks fine, it's probably the best solution for the job you want to do already. The only question I have regarding it is "Do you want to run whatever the do-something code is for every haystack that contains the needle, or just for the first one you find?". If it's the latter, then you should add a break; after the do-something code.
If you're trying to performance-tune your code, then this really isn't the sort of thing you need to worry about. Any change you make to the code as is would be a micro-optimization at best and would have negligible impact for a disproportionate amount of work. If your code performs okay then don't worry about it. If it is suffering performance issues then you need to investigate exactly where the bottlenecks are and why they're occurring, and optimizing those parts of your script. When optimizing it's important to find where you'll gain the maximum benefit from the effort needed.
The biggest and best optimization choice you can make is selecting the right algorithm for what you want to do, everything else is implementation details.
there are many alternatives and ways but depend on your requirement. You can check this link http://us2.php.net/strstr and "See Also" section. Moreover, You can simplified your code rather than using array and loop. Please see the following:
$str = 'hello my name is jon';
if(strpos($str, 'text')!='')
echo "do something";
else
echo "do something";
What is the best way to debug an array so that you can see what values are being stored and in what keys in the array they are being stored at? Also how do you make it so that it's easier to look at visually so that you don't have to keep looking through the array for the key and it's value in the one line print_r() function?
EDIT:
I now realize that print_r() is not the only solution to debugging arrays. So if you have alternate solutions that would be lovely as well to learn more about debugging.
EDIT2:
Ayesh K, ITroubs and Robert Rozas have mentioned both Krumo and Kint this far, if you have others feel free to post them. Also thanks to Raveren for writing Kint!
Every PHP developer should have a function for this. My function is below:
function r($var){
echo '<pre>';
print_r($var);
echo '</pre>';
}
To nicely print data, just call r($data);. If you want more detail, you could use this function:
function d($var){
echo '<pre>';
var_dump($var);
echo '</pre>';
}
here's mine...
demo: http://o-0.me/dump_r/
repo: https://github.com/leeoniya/dump_r.php
composer: https://packagist.org/packages/leeoniya/dump-r
you can restyle it via css if needed.
Everyone suggests print_r which is in core and works really well.
But when it comes to view a large array, print_r() drives me nuts narrowing down the output.
Give a try to krumo.
It nicely prints the array with visual formatting, click-expand and it also gives you the exact array key call that you can simply copy and paste.
<?php
krumo($my_array);
?>
Itroubs mentioned Kint as a better alternative to Krumo. (Thanks ITroubs!)
I use var_dump....now if you want some more, check out this site:
http://raveren.github.io/kint/
and
http://krumo.sourceforge.net/
The best practice to visually see the values/keys in an array is the following:
echo "<pre>".print_r($array,TRUE)."</pre>";
The true is required as it changes it into a string, the output will be:
array(
key1 => value,
key2 => value,
...
)
Quick solution: Open the source code of the page, and you'll see print_r's output in several lines and perfectly indented.
print_r is not one lined (it uses \n as new line, not <br>). Add a <pre>...</pre> around it to show the multiple lines.
print_r() uses \n as its line delimiter. Use <pre> tags or view the page's source code to make it look right. (on Windows, Linux works with \n)
You can either look source code or use var_dump() or print_r() with <pre>...</pre>
I personally, never liked all this fancy stuff, i use print_r() because it's not overwhelming and it gives enough information.
Here is mine:
if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')
{
echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE : </i></strong>'.__LINE__.'<pre>';
print_r($var);
echo '</pre>';
die;
}
This if statement is to ensure that other people don't see what you've printed.
There is a good add-on for Mozila-Firefox and Google Chrome called "user agent switcher", where you can create your custom user agents. So I create a user agent called "Debug", and when I'm working, I change the user agent.
If I use default user agent nothing will happen and the page wont die;, only you and people who also change the user agent to "Debug" will see the printed variable. This is helpful if you want to debug a problem in a production environment, and you don't want the page to die; and it is also good if other people are also working on the project and you don't want to interrupt them by killing the page.
Then I echo out the current File and Line, this is helpful when you work in a framework or CMS or any other big project with thousands of files and folders, and while debugging, if you might forget where you've typed die; or exit; and you need to remember where you've been and which variables you have printed.
I use the NetBeans IDE for PHP development, I have a macro set up so when you select a variable and use it, it will paste this debugging tool to the text editor and put the selection inside a print_r(); function. If you also use NetBeans, you can use this macro:
cut-to-clipboard
"if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')"
insert-break
"{"
insert-break
"echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE :</i></strong>'.__LINE__.'<pre>';"
insert-break
"print_r("
paste-from-clipboard
remove-line-begin
");"
insert-break
"echo '</pre>';"
insert-break
"die;"
You just need to select the $variable and use the macro.
To be honest, I'm surprised that print_r() (print human-readable). There are three native functions which each have their advantages and disadvantages in printing data to a document. As mentioned elsewhere on the page, wrapping your output in <pre> ... </pre> tags will be very beneficial in respecting newlines and tabbing when printing to an html document.
The truth is that ALL php developers, from newbie to hobbyist to professional to grand wizard level 999, need to have the following techniques in their toolbox.
Here is a non-exhaustive demo which exposes some of the differences.
var_export() is the format that I use most often. This function wraps strings in single quotes. This is important in identifying trailing whitespace characters and differentiating numeric types versus string types. To maintain the integrity of the output data and permit instant portability of the data into a runnable context, single quotes and backslashes are escaped -- don't let this trip you up.
print_r() is probably my least-used and the least-informative function when data needs to be inspect. It does not wrap strings in any kind of delimiting character so you will not be able to eyeball invisible characters. It will not escape backslashes, single quotes, or double quotes. It wraps keys in square braces which may cause confusion if your keys contain square braces originally.
var_dump() is uniquely powerful in that it expresses data types AND the byte count for strings. This is hands-down the best tool when there is a risk that you might have unexpected multibyte characters interfering with the success/stability of your script.
Depending on your php version and which function you use, you may see differing values with same input data. Pay careful attention to float values.
debug_zval_dump() very much resembles the output of var_dump(), but also includes a refcount. This native function is not likely to provide any additional benefit relating to "debugging an array".
There are also non-native tools which may be of interest (most of which I've never bothered to use). If you are using a framework, Laravel for instance, offers dd() (dump and die) as a diagnostic helper method. Some devs love the collapsed/expandable styling of this tool, but other devs loudly voice their annoyance at the tedious clicking that is necessary to expose nested levels of data.
As a sideways approach to printing iterable data, you could entertain the idea of echoing a json-encoded string with the JSON_PRETTY_PRINT. This may reveal some things that could cause trouble like multibyte and whitespace characters, but don't forget that this is literally "encoding" the data. In other words, it is converting data from one form to another and it will mutate certain occurrences in the process. Like var_export(), a json encoded string is an excellent form to maintain data integrity when it needs to be tranferred from one place to another (like from your project to your Stack Overflow question!).
Spaces, line breaks, tabs ; are they affect server performance ?
I'm in the road of learning PHP and before I go further with my current coding style, i want to make sure :
Are line breaks and spaces affect the performance of the server ? Usually, I always add them for readibility. for example in the following code :
import('something') ;
$var = 'A' ;
$varb = 'B' ;
switch($var) {
case 'A' :
doSomething() ;
doAnotherThing() ;
break ;
}
if ($var == $varb) { header('Location: somewhere.php') ; }
Summary,
I add space before a semicolon
I add space after and before variable value assignment and comparison
I add space between ) and {
Usually I add a line break after { if the code following it consist of multiple statements.
Inside the curly bracket, I always start with a space before the first statement and ended it with another space after the last statement's semicolon
I always give a 2-space-width tab for every child elements
I always add a space after 'Location:' inside header function.
I always add space before semicolon for each case condition
This style is cool for me, I like it, its tidy and it makes me easier to debug, what i wonder is, will this kind of coding style hurt/burden the system ? Will it makes server slower by re-formatting my codes ? So far i got no formatting error.
Thank you for your kind answers
No. The extra formatting will not affect performance at all*.
Choose the coding style you like -- that is also acceptable for the team/project/existing code -- and, most importantly, be consistent. (Using an editor with customizable syntax formatting is helpful.)
Happy coding.
*While it could be argued that an insignificant increase IO may occur and an insignificant greater amount of symbols must be read by the lexer, the final result is: there will be no performance decrease.
No and yes (but mostly insignificant). Slightly different way thinking about the issue from #pst's answer (not even thinking about disk io) but same end result.
Simplified php behind the scenes - PHP is compiled to bytecodes on runtime. During compile, all spaces and comments are filtered down/out among many other actions.
Filtering out more whitespace from less is mostly insignificant compared with all the other actions.
The compiled bytecodes are what actually gets run.
But let's say you are running a major website, have 1000s of web servers and each php file is getting called millions of times a day. All those previously insignificant bits of time add up. But so does all the other stuff that the compiler is doing. At the point that this all becomes an issue for you, it's time to start looking into PHP caching/accelerators. (Or more likely long before this.)
Basically, those cachers/accelerators cache the compiled bytecodes the first time they are produced after the files are modified. Subsequent calls to the same file skip the compiling phase and go right to the cached compiled bytecodes. At that stage all the whitespace no longer exists. So, it becomes a moot point because they only ever compile once.
I have a php function that I wish to reduce even further.
<?='Testing'?>
Is there a way to reduce this any further?
write Testing without the php tags. php will only interpret code between php tags, everything else will be outputted without any further processing.
Use a shorter word? ;)
Or put it outside the PHP tags (effectively starting and stopping the PHP goodiness).
?>Testing<?
Incidentally - I'm not overly sure what you want to achieve by "shortening". Do you want to make it faster, use less characters? From that example there - I'm not sure you're going to gain a whole lot from any of these examples.
You can assign the value you'd like printed to a short variable name before the output of the script:
<?php
$a = 'Testing';
?>
Then echo out that variable in the output:
<?=$a?>
Can't get any shorter than that.
Is there any speed difference between these two versions?
<?php echo $var; ?>
<?=$var?>
Which do you recommend, and why?
Performance difference is insignificant. Moreover, with use of APC, performance difference is zero, null, nada.
Short tags are problematic within XML, because <? is also markup for XML processing tag. So if you're writing code that should be portable, use the long form.
See short_open_tag description in http://www.php.net/manual/en/ini.core.php
Technically the parser has to parse every character of the longer version, and there's a few more characters for every transfer.
If your webserver doesn't "pre-compile" (ie: cache tokenized PHP pages) then there is a slight performance difference. This should be insignificant except, perhaps, when you start talking about billions of runs.
Performance wise it is insignificant.
Proper usage says to use the longer one, as it is more portable. Personally? I do the shorter one.
No, they are identical. If you like typing a lot use <?php echo $var; ?>, otherwise just save time with <?=$var?>.
Which do you recommend
Neither, unless you really want to allow HTML injection. (99% of the time, you don't.)
<?php echo htmlspecialchars($var); ?>
Or define a function that does echo(htmlspecialchars($arg)) with a shorter name to avoid all that typing.
in php 5.3 short tag ASP-style <% %> support will be deprecated, try to avoid this and rewrite the code to the '<?php echo' format, because u cant use <?xml ?> inline for example.
These two lines of code are identical.
I'm adding a late answer because nobody has demonstrated this yet, but the answer is unequivocally no, there is no performance difference specifically because there is no difference at all in how PHP executes these two lines of code.
The interpreter sees the identical code in both cases. The parser produces the exact same AST, because <?= is fundamentally identical to <?php echo. There is no difference in the instructions the interpreter runs when you write <?= vs <?php echo.
By installing php-ast you can examine the AST produced by both lines of code.
Given these two cases...
# CASE 1
<?php echo $i %>
# CASE 2
<?= $i ?>
The abstract syntax tree for both is identical:
case 1
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
case 2
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
This means PHP cannot tell the difference between these at run time, never mind experiencing some kind of performance difference.
The code to produce this output is as follows, and uses util.php:
<?php
require('util.php');
echo "case 1\n";
echo ast_dump(ast\parse_code('<?php echo $i ?>', $version=50));
echo "\n";
echo "case 2\n";
echo ast_dump(ast\parse_code('<?= $i ?>', $version=50));
echo "\n";
Optimization is irrelevant here. The choice comes down to personal preference, especially since <?= is always available, has nothing to do with short tags, has never been deprecated and is not slated to be removed from the language.
I think the second one requires the short_open_tag (in PHP.ini) to be set to true.
Meaning there is a chance it's turned off on some webservers.
The speed difference depends on how fast you can type those 9 extra characters.
It can also improve the readability of your code, but this is debatable.
If your talking about execution-speed there is no noticable difference.
Don't try to optimize with these, it's useless. Instead, deactivate allow_short_tags (because of problems when loading XML files) and write clean, readable and understandable code.
Even if there may be a slight difference (which is definitely lower than 10%), it's useles to optimize with it. If your scripts are slow, look at your loops first. Most of the time you can win a lot more performance by optimizing the programms flow than by using strange syntax.