<p>I know this sounds like a point-whoring question but let me explain where I'm coming from.</p>

<p>Out of college I got a job at a PHP shop.  I worked there for a year and a half and thought that I had learned all there was to learn about programming.</p>

<p>Then I got a job as a one-man internal development shop at a sizable corporation where all the work was in C#.  In my commitment to the position I started reading a ton of blogs and books and quickly realized how wrong I was to think I knew everything.  I learned about unit testing, dependency injection and decorator patterns, the design principle of loose coupling, the composition over inheritance debate, and so on and on and on - I am still very much absorbing it all.  Needless to say my programming style has changed entirely in the last year.</p>

<p>Now I find myself picking up a php project doing some coding for a friend's start-up and I feel completely constrained as opposed to programming in C#.  It really bothers me that all variables at a class scope have to be referred to by appending '$this->' .  It annoys me that none of the IDEs that I've tried have very good intellisense and that my SimpleTest unit tests methods have to start with the word 'test'.  It drives me crazy that dynamic typing keeps me from specifying implicitly which parameter type a method expects, and that you have to write a switch statement to do method overloads.  I can't stand that you can't have nested namespaces and have to use the :: operator to call the base class's constructor.</p>

<p>Now I have no intention of starting a PHP vs C# debate, rather what I mean to say is that I'm sure there are some PHP features that I either don't know about or know about yet fail to use properly.  I am set in my C# universe and having trouble seeing outside the glass bowl.</p>

<p>So I'm asking, what are your favorite features of PHP?  What are things you can do in it that you can't or are more difficult in the .Net languages?</p>

[{'answer_id': 61403, 'author': 'George Mauer', 'author_id': 5056, 'author_profile': 'https://Stackoverflow.com/users/5056', 'pm_score': 4, 'selected': False, 'text': "<p>Here's one, I like how <strong>setting default values on function parameters</strong> that aren't supplied is much easier:</p>\n\n<pre><code>function MyMethod($VarICareAbout, $VarIDontCareAbout = 'yippie') { }\n</code></pre>\n"}, {'answer_id': 61482, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 7, 'selected': False, 'text': '<p><strong><a href="http://www.php.net/manual/en/language.oop5.magic.php" rel="nofollow noreferrer">Magic Methods</a></strong> are fall-through methods that get called whenever you invoke a method that doesn\'t exist or assign or read a property that doesn\'t exist, among other things.</p>\n\n<pre><code>interface AllMagicMethods {\n    // accessing undefined or invisible (e.g. private) properties\n    public function __get($fieldName);\n    public function __set($fieldName, $value);\n    public function __isset($fieldName);\n    public function __unset($fieldName);\n\n    // calling undefined or invisible (e.g. private) methods\n    public function __call($funcName, $args);\n    public static function __callStatic($funcName, $args); // as of PHP 5.3\n\n    // on serialize() / unserialize()\n    public function __sleep();\n    public function __wakeup();\n\n    // conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)\n    public function __toString();\n\n    // calling the object like a function (e.g. $obj($arg, $arg2))\n    public function __invoke($arguments, $...);\n\n    // called on var_export()\n    public static function __set_state($array);\n}\n</code></pre>\n\n<p>A C++ developer here might notice, that PHP allows overloading some operators, e.g. <code>()</code> or <code>(string)</code>. Actually PHP allows overloading even more, for example the <code>[]</code> operator (<a href="http://www.php.net/manual/en/class.arrayaccess.php" rel="nofollow noreferrer">ArrayAccess</a>), the <code>foreach</code> language construct (<a href="http://www.php.net/manual/en/class.iterator.php" rel="nofollow noreferrer">Iterator</a> and <a href="http://www.php.net/manual/en/class.iteratoraggregate.php" rel="nofollow noreferrer">IteratorAggregate</a>) and the <code>count</code> function (<a href="http://www.php.net/manual/en/class.countable.php" rel="nofollow noreferrer">Countable</a>).</p>\n'}, {'answer_id': 61489, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Stream Handlers</strong> allow you to extend the "FileSystem" with logic that as far as I know is quite difficult to do in most other languages.</p>\n\n<p>For example with the <a href="http://www.phpclasses.org/browse/package/1919.html" rel="nofollow noreferrer">MS-Excel Stream handler</a> you can create a MS Excel file in the following way: </p>\n\n<pre><code>$fp = fopen("xlsfile://tmp/test.xls", "wb");\nif (!is_resource($fp)) { \n    die("Cannot open excel file");\n}\n\n$data= array(\n    array("Name" =&gt; "Bob Loblaw", "Age" =&gt; 50),  \n    array("Name" =&gt; "Popo Jijo", "Age" =&gt; 75),  \n    array("Name" =&gt; "Tiny Tim", "Age" =&gt; 90)\n); \n\nfwrite($fp, serialize($data));\nfclose($fp);\n</code></pre>\n'}, {'answer_id': 61491, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Documentation</strong>. The <a href="http://www.php.net/manual/en/" rel="noreferrer">documentation</a> gets my vote. I haven\'t encountered a more thorough online documentation for a programming language - everything else I have to piece together from various websites and man pages.</p>\n'}, {'answer_id': 61510, 'author': 'MattBelanger', 'author_id': 655, 'author_profile': 'https://Stackoverflow.com/users/655', 'pm_score': 5, 'selected': False, 'text': "<p><strong>Array manipulation.</strong><br>\nTons of tools for working with and manipulating arrays.  It may not be unique to PHP, but I've never worked with a language that made it so easy.</p>\n"}, {'answer_id': 61574, 'author': 'Jan Gorman', 'author_id': 3196, 'author_profile': 'https://Stackoverflow.com/users/3196', 'pm_score': 4, 'selected': False, 'text': "<p>Actually, you're not quite right about that you cannot specify what types a method expects, it does work as you'd expect.</p>\n\n<pre><code>function foo ( array $param0, stdClass $param1 );\n</code></pre>\n\n<p><strong><em>Note:</strong> This only works for 'array' and object names.</em></p>\n\n<p>And so on, and you can even pass in your own classes as expected parameters. Calling the methods/functions with something else will result in a fatal error.</p>\n\n<p>Another hint about a good intellisense in PHP. We use ZendStudio and it will actually work a lot better if you write good PHPDocs for your methods, it will look into those when hinting.</p>\n"}, {'answer_id': 61606, 'author': 'VolkerK', 'author_id': 4833, 'author_profile': 'https://Stackoverflow.com/users/4833', 'pm_score': 5, 'selected': False, 'text': '<p><strong>PHP enabled webspace</strong> is usually less expensive than something with (asp).net.\nYou <i>might</i> call that a feature ;-)</p>\n'}, {'answer_id': 62525, 'author': 'Jrgns', 'author_id': 6681, 'author_profile': 'https://Stackoverflow.com/users/6681', 'pm_score': 6, 'selected': False, 'text': "<p><strong>Variable variables and functions</strong> without a doubt!</p>\n\n<pre><code>$foo = 'bar';\n$bar = 'foobar';\necho $$foo;    //This outputs foobar\n\nfunction bar() {\n    echo 'Hello world!';\n}\n\nfunction foobar() {\n    echo 'What a wonderful world!';\n}\n$foo();    //This outputs Hello world!\n$$foo();    //This outputs What a wonderful world!\n</code></pre>\n\n<p>The same concept applies to object parameters ($some_object->$some_variable);</p>\n\n<p>Very, very nice. Make's coding with loops and patterns very easy, and it's faster and more under control than eval (Thanx @Ross &amp; @Joshi Spawnbrood!).t</p>\n"}, {'answer_id': 62544, 'author': 'f00860', 'author_id': 6851, 'author_profile': 'https://Stackoverflow.com/users/6851', 'pm_score': 1, 'selected': False, 'text': '<p><strong>GOOD:</strong></p>\n\n<ul>\n<li>The wide aceptance of PHP in WebHosting. Nearly every web-hosting service has PHP support.</li>\n<li>Simple things can be solve with simple code. No classes or namespaces are strictly required.</li>\n</ul>\n\n<p><strong>BAD:</strong></p>\n\n<ul>\n<li>There is a ton of functions without any naming-convention. It is so hard to remember all these functions to use it effectively.</li>\n<li>Bad coding habits, all over the web :(</li>\n</ul>\n'}, {'answer_id': 62645, 'author': 'pilsetnieks', 'author_id': 6615, 'author_profile': 'https://Stackoverflow.com/users/6615', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>specifying implicitly which parameter type a method expects</p>\n</blockquote>\n\n<p>Actually, this one is partly possible (at least in PHP5) - you can specify the type for array and object parameters for functions and methods, though you are out of luck in case of scalar types.</p>\n\n<pre><code>class Bar\n{\n    public function __construct(array $Parameters, Bar $AnotherBar){}\n}\n</code></pre>\n\n<p>Apart from this one and the magic methods Allain mentioned, I also find the interfaces provided by SPL (Standard PHP library) indispensible - you can implement the necessary methods in your class, for example, I particulary like the ArrayAccess and Iterator interfaces, that allow using an object like an associative array or iterating over it just like any simple array.</p>\n'}, {'answer_id': 63363, 'author': 'Annika Backstrom', 'author_id': 7675, 'author_profile': 'https://Stackoverflow.com/users/7675', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://us.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting" rel="nofollow noreferrer"><strong>Typecasting</strong></a> and the <a href="http://us.php.net/manual/en/book.ctype.php" rel="nofollow noreferrer">ctype_*</a> functions become important to ensure clean data. I have made extensive use of <a href="http://us.php.net/manual/en/language.exceptions.php" rel="nofollow noreferrer">exceptions</a> lately, which has greatly simplified my error handling code.</p>\n\n<p>I wouldn\'t say the language has lots of killer features. (At least, I don\'t find much occasion to seek them out.) I like that the language is unobtrusive.</p>\n'}, {'answer_id': 64475, 'author': 'user8134', 'author_id': 8134, 'author_profile': 'https://Stackoverflow.com/users/8134', 'pm_score': 7, 'selected': False, 'text': "<p><strong>Arrays</strong>. Judging from the answers to this question I don't think people fully appreciate just how easy and useful Arrays in PHP are. PHP Arrays act as lists, maps, stacks and generic data structures all at the same time. Arrays are implemented in the language core and are used all over the place which results in good CPU cache locality. Perl and Python both use separate language constructs for lists and maps resulting in more copying and potentially confusing transformations.</p>\n"}, {'answer_id': 65379, 'author': 'levhita', 'author_id': 7946, 'author_profile': 'https://Stackoverflow.com/users/7946', 'pm_score': 2, 'selected': False, 'text': "<p>How extremely easy is to find PHP related things Examples, Applications, Classes, Documentation, Frameworks, etc...</p>\n\n<p>All over the web, it's the easiest language to learn when going commando(by yourself), and also the one with more value for your time.</p>\n\n<p>After learning PHP might put  CMS with joomla, a blog with wordpress, etc.... </p>\n"}, {'answer_id': 71396, 'author': 'Egon_Freeman', 'author_id': 456146, 'author_profile': 'https://Stackoverflow.com/users/456146', 'pm_score': 4, 'selected': False, 'text': "<p>a) the <strong>manual</strong> -- extremely comprehensive, up-to-date and just a huge source for inspiration while problem-solving - stuck? browse/search the manual, it'll come to you</p>\n\n<p>b) <strong>arrays</strong> - they're plastic, they're associatively indexed, they can be easily nested (!) to make up some wild data structures, and there's a multitude of functions just for array operations alone. Oh, and did I mention treating separate variables as an array of values?</p>\n\n<p>c) <strong>eval()</strong> and similar constructs (like dynamic variable and function names) which allow for much greater flexibility (and are still relatively safe provided you know what you're doing) - nothing beats a program that basically defines its own process flow (or even specific execution) on the fly</p>\n\n<p>d) most probably the easiest thing to overlook: as almost everything in the ZEND engine is a <strong>zVal</strong> (which in essence is a collection of pointer references), the ability to return about anything as a function return value</p>\n\n<p><br>\nAlso, I'd like to point out one great feature, but one which is related more to PHP source than the language (and so - listed separately):</p>\n\n<p>e) the ease of writing <strong>C extensions</strong> (mostly interfaces for other objects like OpenAL or SDL) - great source code structure and about as many powerfull tools on the 'inside' as there are on the 'outside' - if you ever need to expand the functionality just that little bit further.</p>\n"}, {'answer_id': 72276, 'author': 'Chris Ridenour', 'author_id': 12049, 'author_profile': 'https://Stackoverflow.com/users/12049', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Easiness</strong>. The greatest feature is how easy it is for new developers to sit down and write "working" scripts and understand the code.  </p>\n\n<p>The worst feature is how easy it is for new developers to sit down and write "working" scripts and think they understand the code.</p>\n\n<p>The <strong>openness of the community</strong> surrounding PHP and the massive amounts of PHP projects available as open-source is a lot less intimidating for someone entering the development world and like you, can be a stepping stone into more mature languages.  </p>\n\n<p>I won\'t debate the technical things as many before me have but if you look at PHP as a community rather than a web language, a community that clearly embraced you when you started developing, the benefits really speak for themselves.</p>\n'}, {'answer_id': 114001, 'author': 'Armin Ronacher', 'author_id': 19990, 'author_profile': 'https://Stackoverflow.com/users/19990', 'pm_score': 6, 'selected': False, 'text': '<p>One not so well known feature of PHP is <a href="http://php.net/manual/en/function.extract.php" rel="nofollow noreferrer"><strong><code>extract()</code></strong></a>, a function that unpacks an associative array into the local namespace.  This probably exists for the autoglobal abormination but is very useful for templating:</p>\n\n<pre><code>function render_template($template_name, $context, $as_string=false)\n{\n    extract($context);\n    if ($as_string)\n        ob_start();\n    include TEMPLATE_DIR . \'/\' . $template_name;\n    if ($as_string)\n        return ob_get_clean();\n}\n</code></pre>\n\n<p>Now you can use <code>render_template(\'index.html\', array(\'foo\' =&gt; \'bar\'))</code> and only <code>$foo</code> with the value <code>"bar"</code> appears in the template.</p>\n'}, {'answer_id': 114028, 'author': 'Andrew Taylor', 'author_id': 1776, 'author_profile': 'https://Stackoverflow.com/users/1776', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m a bit like you, I\'ve coded PHP for over 8 years. I had to take a .NET/C# course about a year ago and I really enjoyed the C# language (hated ASP.NET) but it made me a better PHP developer.</p>\n\n<p>PHP as a language is pretty poor, but, I\'m extremely quick with it and the LAMP stack is awesome. The end product far outweighs the sum of the parts.</p>\n\n<p>That said, in answer to your question:</p>\n\n<p><a href="http://uk.php.net/SPL" rel="nofollow noreferrer">http://uk.php.net/SPL</a></p>\n\n<p>I love the <strong>SPL</strong>, the collection class in C# was something that I liked as soon as I started with it. Now I can have my cake and eat it.</p>\n\n<p>Andrew</p>\n'}, {'answer_id': 114047, 'author': 'Ian', 'author_id': 4396, 'author_profile': 'https://Stackoverflow.com/users/4396', 'pm_score': 3, 'selected': False, 'text': '<p>Built in filters for parsing variables against specific predefined types - as well as covering the basics (int/float etc), extends to covering emails, urls and even if a variable is a valid regular expression.</p>\n\n<p><a href="http://ch2.php.net/manual/en/book.filter.php" rel="nofollow noreferrer">http://ch2.php.net/manual/en/book.filter.php</a></p>\n'}, {'answer_id': 163857, 'author': 'Willem', 'author_id': 15447, 'author_profile': 'https://Stackoverflow.com/users/15447', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://php.net/manual/de/language.oop5.autoload.php" rel="nofollow noreferrer"><strong><code>__autoload()</code></strong></a> (class-) files aided by <code>set_include_path()</code>.</p>\n\n<p>In PHP5 it is now unnecessary to specify long lists of "include_once" statements when doing decent OOP.</p>\n\n<p>Just define a small set of directory in which class-library files are sanely structured, and set the auto include path:</p>\n\n<pre><code>set_include_path(get_include_path() . PATH_SEPARATOR . \'../libs/\');`\n</code></pre>\n\n<p>Now the <code>__autoload()</code> routine:</p>\n\n<pre><code>function __autoload($classname) {\n    // every class is stored in a file "libs/classname.class.php"\n\n    // note: temporary alter error_reporting to prevent WARNINGS\n    // Do not suppress errors with a @ - syntax errors will fail silently!\n\n    include_once($classname . \'.class.php\');\n}\n</code></pre>\n\n<p>Now PHP will automagically include the needed files on-demand, conserving parsing time and memory.</p>\n'}, {'answer_id': 173907, 'author': 'e-satis', 'author_id': 9951, 'author_profile': 'https://Stackoverflow.com/users/9951', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Then "and print" trick</strong></p>\n\n<pre><code>&lt;?php $flag and print "Blah" ?&gt;\n</code></pre>\n\n<p>Will echo Blah if $flag is true. DOES NOT WORK WITH ECHO.</p>\n\n<p>This is very handy in template and replace the ? : that are not really easy to read.</p>\n'}, {'answer_id': 255623, 'author': 'Dean Rather', 'author_id': 14966, 'author_profile': 'https://Stackoverflow.com/users/14966', 'pm_score': 7, 'selected': False, 'text': '<p>The <b>standard class</b> is a neat container. I only learned about it recently.</p>\n\n<p>Instead of using an array to hold serveral attributes</p>\n\n<pre><code>$person = array();\n$person[\'name\'] = \'bob\';\n$person[\'age\'] = 5;\n</code></pre>\n\n<p>You can use a standard class</p>\n\n<pre><code>$person = new stdClass();\n$person-&gt;name = \'bob\';\n$person-&gt;age = 5;\n</code></pre>\n\n<p>This is particularly helpful when accessing these variables in a string</p>\n\n<pre><code>$string = $person[\'name\'] . \' is \' . $person[\'age\'] . \' years old.\';\n// vs\n$string = "$person-&gt;name is $person-&gt;age years old.";\n</code></pre>\n'}, {'answer_id': 432502, 'author': 'Lucacri', 'author_id': 89884, 'author_profile': 'https://Stackoverflow.com/users/89884', 'pm_score': 5, 'selected': False, 'text': '<p>One nice feature of PHP is the <strong>CLI</strong>. It\'s not so "promoted" in the documentation but if you need routine scripts / console apps, using cron + php cli is really fast to develop!</p>\n'}, {'answer_id': 526917, 'author': 'Michał Tatarynowicz', 'author_id': 49564, 'author_profile': 'https://Stackoverflow.com/users/49564', 'pm_score': 6, 'selected': False, 'text': '<p>You can take advantage of the fact that the <code>or</code> operator has lower precedence than <code>=</code> to do this:</p>\n\n<pre><code>$page = (int) @$_GET[\'page\'] \n  or $page = 1;\n</code></pre>\n\n<p>If the value of the first assignment evaluates to <code>true</code>, the second assignment is ignored. Another example:</p>\n\n<pre><code>$record = get_record($id) \n  or throw new Exception("...");\n</code></pre>\n'}, {'answer_id': 551988, 'author': 'Bob Fanger', 'author_id': 19165, 'author_profile': 'https://Stackoverflow.com/users/19165', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Quick and dirty</strong> is the default.<br>\nThe language is filled with useful shortcuts, This makes PHP the perfect candidate for (small) projects that have a short time-to-market.\nNot that clean PHP code is impossible, it just takes some extra effort and experience.</p>\n\n<p>But I love PHP because it lets me express what I want without typing an essay.</p>\n\n<p>PHP:</p>\n\n<pre><code>if (preg_match("/cat/","one cat")) {\n   // do something\n}\n</code></pre>\n\n<p>JAVA:</p>\n\n<pre><code>import java.util.regex.*;\nPattern p = Pattern.compile("cat");\nMatcher m = p.matcher("one cat")\nif (m.find()) {\n  // do something\n}\n</code></pre>\n\n<p>And yes, that includes not typing <strong>Int</strong>.</p>\n'}, {'answer_id': 665524, 'author': 'thomasrutter', 'author_id': 53212, 'author_profile': 'https://Stackoverflow.com/users/53212', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://au2.php.net/strtr" rel="nofollow noreferrer"><strong>strtr()</strong></a></p>\n\n<p>It\'s extremely fast, so much that you would be amazed.  Internally it probably uses some crazy b-tree type structure to arrange your matches by their common prefixes.  I use it with over 200 find and replace strings and it still goes through 1MB in less than 100ms.  For all but trivially small strings strtr() is even significantly faster than strtolower() at doing the exact same thing, even taking character set into account.  You could probably write an entire parser using successive strtr calls and it\'d be faster than the usual regular expression match, figure out token type, output this or that, next regular expression kind of thing.</p>\n\n<p>I was writing a text normaliser for splitting text into words, lowercasing, removing punctuation etc and strtr was my Swiss army knife, it beat the pants off regular expressions or even str_replace().</p>\n'}, {'answer_id': 665540, 'author': 'Christian Studer', 'author_id': 6260, 'author_profile': 'https://Stackoverflow.com/users/6260', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Date functions</strong>. I have to handle a lot of time information and date strings all day long, so functions like <a href="http://www.php.net/strftime" rel="nofollow noreferrer">strftime()</a> and <a href="http://www.php.net/strtotime" rel="nofollow noreferrer">strtotime()</a> are just awesome.</p>\n'}, {'answer_id': 665660, 'author': 'Jamol', 'author_id': 66611, 'author_profile': 'https://Stackoverflow.com/users/66611', 'pm_score': 5, 'selected': False, 'text': '<p>Probably not many know that it is possible to specify constant "variables" as default values for function parameters:</p>\n\n<pre><code>function myFunc($param1, $param2 = MY_CONST)\n{\n//code...\n}\n</code></pre>\n\n<p><strong>Strings</strong> can be used <strong>as</strong> if they were <strong>arrays</strong>:</p>\n\n<pre><code>$str = \'hell o World\';\necho $str; //outputs: "hell o World"\n\n$str[0] = \'H\';\necho $str; //outputs: "Hell o World"\n\n$str[4] = null;\necho $str; //outputs: "Hello World"\n</code></pre>\n'}, {'answer_id': 666947, 'author': 'Strae', 'author_id': 80363, 'author_profile': 'https://Stackoverflow.com/users/80363', 'pm_score': 2, 'selected': False, 'text': "<p>Well, the <strong>community</strong> is in the first place for me.\nWhatever can your problem be, you'll always find someone who had it before and almost every time a solution... and sometimes I've seen a completely free share of ideas, ways to approach a single problem.</p>\n\n<p>I'm trying to learn Python now (to grow up as... well.. programmer, can that be?) and the most useful thing of Python is the indentation.\nI love the PHP indentation, the $ mark for sign the variables, curly braces for loops and cycles, well, those smart things keep my code very easy to understand (even if the one who's wrote the code was little..messy up.. 'spaghetti-code', mh?)</p>\n\n<p><strong>Arrays</strong>, in PHP are pretty simple and powerful.</p>\n\n<p><strong>Databases</strong>: MySQL, Postrgee, sql; you can use almost every kind of databases.. easily.</p>\n\n<p>Quick: logically depends by how is the code wrote, but usually PHP is pretty <strong>fast for small/medium application</strong> (as it lose wheel in bigger application).</p>\n"}, {'answer_id': 794461, 'author': 'Luc M', 'author_id': 14673, 'author_profile': 'https://Stackoverflow.com/users/14673', 'pm_score': 3, 'selected': False, 'text': "<p>You can easily add an element to an array.</p>\n\n<pre><code>$my_array = array();\n$my_array[] = 'first element';\n$my_array[] = 'second element';\n</code></pre>\n\n<p>Element may be anything: object, array, scalar...</p>\n"}, {'answer_id': 810635, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>You can use <strong>minus character in variable names</strong> like this:</p>\n\n<pre><code>class style\n{\n  ....\n  function set_bg_colour($c)\n  {\n    $this-&gt;{'background-color'} = $c;\n  }\n}\n</code></pre>\n\n<p>Why use it? No idea: maybe for a CSS model? Or some weird JSON you need to output. It's an odd feature :)</p>\n"}, {'answer_id': 844512, 'author': 'Jason', 'author_id': 99401, 'author_profile': 'https://Stackoverflow.com/users/99401', 'pm_score': 2, 'selected': False, 'text': "<p>I'm partial to the other PHP users out there.  It's easy to get answers and direction when necessary.</p>\n"}, {'answer_id': 886384, 'author': 'zombat', 'author_id': 81205, 'author_profile': 'https://Stackoverflow.com/users/81205', 'pm_score': 6, 'selected': False, 'text': '<p>I love <a href="http://www.php.net/manual/en/features.remote-files.php" rel="nofollow noreferrer"><strong>remote files</strong></a>.  For web development, this kind of feature is exceptionally useful.</p>\n\n<p>Need to work with the contents of a web page?  A simple </p>\n\n<pre><code>$fp = fopen(\'http://example.com\');\n</code></pre>\n\n<p>and you\'ve got a file handle ready to go, just like any other normal file.</p>\n\n<p>Or how about reading a remote file or web page directly in to a string?  </p>\n\n<pre><code>$str = file_get_contents(\'http://example.com/file\');\n</code></pre>\n\n<p>The usefulness of this particular method is hard to overstate.</p>\n\n<p>Want to analyze a remote image?  How about doing it via FTP?</p>\n\n<pre><code>$imageInfo = getimagesize(\'ftp://user:password@ftp.example.com/image/name.jpg\');\n</code></pre>\n\n<p>Almost any PHP function that works with files can work with a remote file.  You can even <code>include()</code> or <code>require()</code> code files remotely this way.</p>\n'}, {'answer_id': 1023029, 'author': 'Sam152', 'author_id': 59730, 'author_profile': 'https://Stackoverflow.com/users/59730', 'pm_score': 5, 'selected': False, 'text': "<h2>Fast block comments</h2>\n\n<pre><code>/*\n    die('You shall not pass!');\n//*/\n\n\n//*\n    die('You shall not pass!');\n//*/\n</code></pre>\n\n<p>These comments allow you to toggle if a code block is commented with one character.</p>\n"}, {'answer_id': 1024737, 'author': 'redwall_hp', 'author_id': 126564, 'author_profile': 'https://Stackoverflow.com/users/126564', 'pm_score': 2, 'selected': False, 'text': "<p>Let's see...</p>\n\n<ol>\n<li><p>Ternary operators. They work wonders for processing checkboxes in form results.</p>\n\n<p>$var = ($_POST['my_checkbox']=='checked') ? TRUE : FALSE;</p></li>\n<li><p>All of the wonderful string and array processing functions are worth trawling through. strtotime(), strlen(), and strpos() are a few of my favorites.</p></li>\n<li><p>The SimpleXML class and json_decode() function. Call a REST API or RSS feed with file_get_contents(), parse it effortlessly with one of those tools, and you're done.</p></li>\n</ol>\n"}, {'answer_id': 1024858, 'author': 'Justin Johnson', 'author_id': 126562, 'author_profile': 'https://Stackoverflow.com/users/126562', 'pm_score': 4, 'selected': False, 'text': '<p>Error suppression via the <a href="http://www.php.net/manual/en/language.operators.errorcontrol.php" rel="nofollow noreferrer">error control operator, @</a>, should almost never be used.  It promotes lazy and non-defensive coding practices by simply ignoring errors, creates debugging nightmares since errors of all types--even fatal ones--will be suppressed, and, in some cases, can cause a hit to performance (especially when suppressing large quantities of errors).</p>\n'}, {'answer_id': 1024875, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>preg_split(), array_intersect(), and array_intersect_key().</p>\n'}, {'answer_id': 1024891, 'author': 'dcousineau', 'author_id': 20265, 'author_profile': 'https://Stackoverflow.com/users/20265', 'pm_score': 5, 'selected': False, 'text': "<p>The <code>static</code> keyword is useful outside of a OOP standpoint. You can quickly and easily implement 'memoization' or function caching with something as simple as:</p>\n\n<pre><code>&lt;?php\nfunction foo($arg1)\n{\n    static $cache;\n\n    if( !isset($cache[md5($arg1)]) )\n    {\n        // Do the work here\n        $cache[md5($arg1)] = $results;\n    }\n\n    return $cache[md5($arg1)];\n}\n?&gt;\n</code></pre>\n\n<p>The <code>static</code> keyword creates a variable that persists only within the scope of that function past the execution. This technique is great for functions that hit the database like <code>get_all_books_by_id(...)</code> or <code>get_all_categories(...)</code> that you would call more than once during a page load.</p>\n\n<p><em>Caveat:</em> Make sure you find out the best way to make a key for your hash, in just about every circumstance the <code>md5(...)</code> above is NOT a good decision (speed and output length issues), I used it for illustrative purposes. <code>sprintf('%u', crc32(...))</code> or <code>spl_object_hash(...)</code> may be much better depending on the context.</p>\n"}, {'answer_id': 1024914, 'author': 'MSpreij', 'author_id': 126584, 'author_profile': 'https://Stackoverflow.com/users/126584', 'pm_score': 5, 'selected': False, 'text': '<p>My list.. most of them fall more under the "hidden features" than the "favorite features" (I hope!), and not all are useful, but .. yeah.  </p>\n\n<pre><code>// swap values. any number of vars works, obviously  \nlist($a, $b) = array($b, $a);\n\n// nested list() calls "fill" variables from multidim arrays:  \n$arr = array(  \n  array(\'aaaa\', \'bbb\'),  \n  array(\'cc\', \'d\')  \n);  \nlist(list($a, $b), list($c, $d)) = $arr;  \necho "$a $b $c $d"; // -&gt; aaaa bbb cc d  \n\n// list() values to arrays  \nwhile (list($arr1[], $arr2[], $arr3[]) = mysql_fetch_row($res)) { .. }  \n// or get columns from a matrix  \nforeach($data as $row) list($col_1[], $col_2[], $col_3[]) = $row;\n\n// abusing the ternary operator to set other variables as a side effect:  \n$foo = $condition ? \'Yes\' . (($bar = \'right\') &amp;&amp; false) : \'No\' . (($bar = \'left\') &amp;&amp; false);  \n// boolean False cast to string for concatenation becomes an empty string \'\'.  \n// you can also use list() but that\'s so boring ;-)  \nlist($foo, $bar) = $condition ? array(\'Yes\', \'right\') : array(\'No\', \'left\');\n</code></pre>\n\n<p>You can nest ternary operators too, comes in handy sometimes.</p>\n\n<pre><code>// the strings\' "Complex syntax" allows for *weird* stuff.  \n// given $i = 3, if $custom is true, set $foo to $P[\'size3\'], else to $C[\'size3\']:  \n$foo = ${$custom?\'P\':\'C\'}[\'size\'.$i];  \n$foo = $custom?$P[\'size\'.$i]:$C[\'size\'.$i]; // does the same, but it\'s too long ;-)  \n// similarly, splitting an array $all_rows into two arrays $data0 and $data1 based  \n// on some field \'active\' in the sub-arrays:  \nforeach ($all_rows as $row) ${\'data\'.($row[\'active\']?1:0)}[] = $row;\n\n// slight adaption from another answer here, I had to try out what else you could  \n// abuse as variable names.. turns out, way too much...  \n$string = \'f.&gt; &lt;!-? o+\';  \n${$string} = \'asdfasf\';  \necho ${$string}; // -&gt; \'asdfasf\'  \necho $GLOBALS[\'f.&gt; &lt;!-? o+\']; // -&gt; \'asdfasf\'  \n// (don\'t do this. srsly.)\n\n${\'\'} = 456;  \necho ${\'\'}; // -&gt; 456  \necho $GLOBALS[\'\']; // -&gt; 456  \n// I have no idea.  \n</code></pre>\n\n<p>Right, I\'ll stop for now :-)</p>\n\n<hr>\n\n<p>Hmm, it\'s been a while..</p>\n\n<pre><code>// just discovered you can comment the hell out of php:\n$q/* snarf */=/* quux */$_GET/* foo */[/* bar */\'q\'/* bazz */]/* yadda */;\n</code></pre>\n\n<p>So, just discovered you can pass any string as a method name IF you enclose it with curly brackets. You can\'t define any string as a method alas, but you can catch them with __call(), and process them further as needed. Hmmm....</p>\n\n<pre><code>class foo {\n  function __call($func, $args) {\n    eval ($func);\n  }\n}\n\n$x = new foo;\n$x-&gt;{\'foreach(range(1, 10) as $i) {echo $i."\\n";}\'}();\n</code></pre>\n\n<p>Found this little gem in Reddit comments:</p>\n\n<pre><code>$foo = \'abcde\';\n$strlen = \'strlen\';\necho "$foo is {$strlen($foo)} characters long."; // "abcde is 5 characters long."\n</code></pre>\n\n<p>You can\'t call functions inside {} directly like this, but you <em>can</em> use variables-holding-the-function-name and call those! (*and* you can use variable variables on it, too)</p>\n'}, {'answer_id': 1025061, 'author': 'artlung', 'author_id': 63094, 'author_profile': 'https://Stackoverflow.com/users/63094', 'pm_score': 5, 'selected': False, 'text': '<p>The single most useful thing about PHP code is that if I don\'t quite understand a function I see I can look it up by using a browser and typing:</p>\n\n<blockquote>\n  <p><a href="http://php.net/function" rel="nofollow noreferrer">http://php.net/function</a></p>\n</blockquote>\n\n<p>Last month I saw the "range" function in some code. It\'s one of the hundreds of functions I\'d managed to never use but turn out to be really useful:</p>\n\n<blockquote>\n  <p><a href="http://php.net/range" rel="nofollow noreferrer">http://php.net/range</a></p>\n</blockquote>\n\n<p>That url is an alias for <a href="http://us2.php.net/manual/en/function.range.php" rel="nofollow noreferrer">http://us2.php.net/manual/en/function.range.php</a>. That simple idea, of <strong>mapping functions and keywords to urls</strong>, is awesome.</p>\n\n<p>I wish other languages, frameworks, databases, operating systems has as simple a mechanism for looking up documentation.</p>\n'}, {'answer_id': 1025143, 'author': 'staticsan', 'author_id': 28832, 'author_profile': 'https://Stackoverflow.com/users/28832', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m a little surprised no-one has mentioned it yet, but one of my favourite tricks with arrays is using the plus operator. It is a little bit like <code>array_merge()</code> but a little simpler. I\'ve found it\'s usually what I want. In effect, it takes all the entries in the RHS and makes them appear in a copy of the LHS, overwriting as necessary (i.e. it\'s non-commutative). Very useful for starting with a "default" array and adding some real values all in one hit, whilst leaving default values in place for values not provided.</p>\n\n<p>Code sample requested:</p>\n\n<pre><code>// Set the normal defaults.\n$control_defaults = array( \'type\' =&gt; \'text\', \'size\' =&gt; 30 );\n\n// ... many lines later ...\n\n$control_5 = $control_defaults + array( \'name\' =&gt; \'surname\', \'size\' =&gt; 40 );\n// This is the same as:\n// $control_5 = array( \'type\' =&gt; \'text\', \'name\' =&gt; \'surname\', \'size\' =&gt; 40 );\n</code></pre>\n'}, {'answer_id': 1025183, 'author': 'noripcord', 'author_id': 84824, 'author_profile': 'https://Stackoverflow.com/users/84824', 'pm_score': 0, 'selected': False, 'text': '<p>This is great:</p>\n\n<pre><code>//file page_specific_funcs.inc\n\nfunction doOtherThing(){\n\n}\n\nclass MyClass{\n\n}\n\n//end file\n\n//file.php\n\nfunction doSomething(){\n  include("page_specific_funcs.inc");\n\n  $var = new MyClass(); \n\n}\n//end of file.php\n</code></pre>\n\n<blockquote>\n  <p>"page_specific_funcs.inc" file <strong>is\n  only included</strong> if doSomething gets\n  called. The declaration of classes,\n  funcs, etc., inside methods works\n  perfectly.</p>\n</blockquote>\n'}, {'answer_id': 1025634, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': "<p>Boolean casting, which is particularly helpful for redwall_hp's first example, above.</p>\n\n<p>Instead of:</p>\n\n<pre><code>$var = ($_POST['my_checkbox']=='checked') ? TRUE : FALSE;\n</code></pre>\n\n<p>You can type:</p>\n\n<pre><code>$var = !!($_POST['my_checkbox']=='checked');\n</code></pre>\n"}, {'answer_id': 1026758, 'author': 'Darren Newton', 'author_id': 12799, 'author_profile': 'https://Stackoverflow.com/users/12799', 'pm_score': 6, 'selected': False, 'text': '<p><strong><a href="http://us.php.net/manual/en/function.range.php" rel="nofollow noreferrer">Range()</a></strong> isn\'t hidden per se, but I still see a lot of people iterating with:</p>\n\n<pre><code>for ($i=0; $i &lt; $x; $i++) { \n    // code...\n}\n</code></pre>\n\n<p>when they could be using:</p>\n\n<pre><code>foreach (range(0, 12) as $number) {\n    // ...\n}\n</code></pre>\n\n<p>And you can do simple things like</p>\n\n<pre><code>foreach (range(date("Y"), date("Y")+20) as $i)\n{\nprint "\\t&lt;option value=\\"{$i}\\"&gt;{$i}&lt;/option&gt;\\n";\n}\n</code></pre>\n'}, {'answer_id': 1027553, 'author': 'aviv', 'author_id': 112601, 'author_profile': 'https://Stackoverflow.com/users/112601', 'pm_score': -1, 'selected': False, 'text': "<p>As far as i know, you can Implicit parameter type in function call:</p>\n\n<pre><code>function getInt(int $v)\n{\n     echo $v;\n}\n\ngetInt(5); // will work\ngetInt('hello'); // will fail\n</code></pre>\n"}, {'answer_id': 1027577, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Definitely the magic and overloading methods. Allain cited __get(), __set(), __call() and __toString(), but I also love __wakeup() and __sleep().</p>\n\n<p>This magic methods are called when the object is serialized (sleep) and deserialized (wakeup). This feature ables making things like serializable Database-wrappers, which i am using in an application:</p>\n\n<pre><code>Class Connection {\n   private $dsn;\n   private $connection;\n   ...\n   public __wakeup() {\n      $this-&gt;connection = ADONewConnection();\n   }\n}\n</code></pre>\n\n<p>In this way i can "save" connections in $_SESSION, etc.</p>\n'}, {'answer_id': 1027667, 'author': 'David', 'author_id': 122118, 'author_profile': 'https://Stackoverflow.com/users/122118', 'pm_score': 1, 'selected': False, 'text': '<p>The json_encode/decode functions in php are pretty useful, though not very hidden.</p>\n'}, {'answer_id': 1027828, 'author': 'Eric', 'author_id': 119301, 'author_profile': 'https://Stackoverflow.com/users/119301', 'pm_score': 4, 'selected': False, 'text': '<p>Besides instant access to start coding away at anything you need for a website?</p>\n\n<p>Besides magic methods and reflections, some interesting functions are:</p>\n\n<ol>\n<li><a href="http://ca.php.net/serialize" rel="noreferrer"><code>serialize</code></a> / <a href="http://ca.php.net/unserialize" rel="noreferrer"><code>unserialize</code></a> - state saving goodness via sql, cookies, processes, flatfile. good stuff.</li>\n<li><a href="http://ca.php.net/json_encode" rel="noreferrer"><code>json_encode</code></a> / <a href="http://ca.php.net/json_decode" rel="noreferrer"><code>json_decode</code></a> - instant AJAX fun</li>\n<li><a href="http://ca.php.net/get_class" rel="noreferrer"><code>get_class</code></a> - helpful for those weary loose-typing moments </li>\n<li><a href="http://ca.php.net/call_user_func_array" rel="noreferrer"><code>call_user_func_array</code></a> - powerful when you can work with your code as strings (think dynamic)</li>\n<li><a href="http://ca.php.net/method_exists" rel="noreferrer"><code>method_exists</code></a> - reflection</li>\n<li><a href="http://ca.php.net/func_num_args" rel="noreferrer"><code>func_num_arg</code>s</a> / <a href="http://ca.php.net/func_get_args" rel="noreferrer"><code>func_get_arg</code></a> - unknown arguments ftw</li>\n<li><a href="http://ca.php.net/set_error_handler" rel="noreferrer"><code>set_error_handler</code></a> / <a href="http://ca.php.net/set_exception_handler" rel="noreferrer"><code>set_exception_handler</code></a> - very good debugging capabilities for a scripting language</li>\n</ol>\n'}, {'answer_id': 1029100, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p><strong>HEREDOC</strong> syntax is my favourite hidden feature. Always difficult to find as you can\'t Google for &lt;&lt;&lt; but it stops you having to escape large chunks of HTML and still allows you to drop variables into the stream.</p>\n\n<pre><code>echo &lt;&lt;&lt;EOM\n  &lt;div id="someblock"&gt;\n    &lt;img src="{$file}" /&gt;\n  &lt;/div&gt;\nEOM;\n</code></pre>\n'}, {'answer_id': 1029114, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I also like the difference between \' and ".</p>\n\n<pre><code>$foo = \'Bob\';\necho \'My name is {$foo}\'; // Doesn\'t swap the variable\necho "My name is {$foo}"; // Swaps the variable\n</code></pre>\n\n<p>Therefore, if your string doesn\'t need variable swapping, don\'t use a ", it\'s a waste of time. I see lots of people declaring strings with " all the time.</p>\n\n<p>Note: I use { } as it makes my variables stand out more.</p>\n'}, {'answer_id': 1029599, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s lots of gems hidden in the Standard PHP Library. Array access allows you to build an object that works to an array interface but add your own functionality on top.</p>\n\n<p>Also when you create an ArrayAccess object by setting a flag in the constructor you can read and write an object as either an array or an object. Here\'s an example:</p>\n\n<pre><code>$obj = new ArrayObject(array("name"=&gt;"bob", "email"=&gt;"bob@example.com"),2);\n$obj-&gt;fullname = "Bob Example";\necho $obj["fullname"];\n$obj["fullname"]="Bobby Example";\necho $obj-&gt;fullname;\n</code></pre>\n'}, {'answer_id': 1053080, 'author': 'nightingale2k1', 'author_id': 119139, 'author_profile': 'https://Stackoverflow.com/users/119139', 'pm_score': -1, 'selected': False, 'text': '<p>the hidden features that I love from php:\n1. easy to learn (also easy to missused it .. ie: bad programming habits. like you can type $something = "1" ; and then you did $something += 3 ; and suddenly $something becomes an integer .. without error message/freaking exceptions, like those in java)</p>\n\n<ol start="2">\n<li>lots of library. go to phpclasses.org and I almost got everything from there.</li>\n<li>lots of web using it. Love it or hate it .. that\'s the fact ! :)</li>\n<li>simple, small and easy to maintenance. you just install xampplite + vim (my favourite) on your portable devices. </li>\n<li>cheap !!! as cheap as a beer ... for example: hosting. compared to java or .net host, php host really cheap and you can get free one from some websites (although they will put some banners / hidden thing inside your website)</li>\n<li>the documentation for php was very good !! that\'s the main reason i am stick to php for about 6 years (although I did some projects using Groovy/Grails)</li>\n</ol>\n'}, {'answer_id': 1061640, 'author': 'Shane H', 'author_id': 60247, 'author_profile': 'https://Stackoverflow.com/users/60247', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Output buffering</strong> via ob_start() is far more useful than most realize. The first hidden feature here is that ob_start accepts a callback: </p>\n\n<pre><code>function twiterize($text) {\n    // Replace @somename with the full twitter handle\n    return preg_replace("(\\s+)@(\\w)+(\\s+)", "http://www.twitter.com/${2}", $text);\n}\n\nob_start(twiterize);\n</code></pre>\n\n<p>Secondly, you can nest output buffers... Using the previous example: </p>\n\n<pre><code>ob_start(parseTemplate);\n // ... \n ob_start(twiterize);\n   // ...\n ob_end_flush();\n // ... \nob_end_flush();\n</code></pre>\n\n<p>Help contents, text ads, dictionary/index functionality, linkify, link-redirection for tracking purposes, templating engine, all these things are very easy by using different combinations of these 2 things.</p>\n'}, {'answer_id': 1066936, 'author': 'djn', 'author_id': 9673, 'author_profile': 'https://Stackoverflow.com/users/9673', 'pm_score': 3, 'selected': False, 'text': '<p>Well, I\'ve recently delivered my first GUI application to a paying customer - written in PHP! It gathers data from a barcode reader or from GUI pushbuttons, checkboxes, radio buttons or text fields, stores to SQLite or remote MySQL, launches other Windows apps, sends zipped XML reports as email attachments, encrypts and decrypts stored data and even plays a sound when done.</p>\n\n<p>Did it with <a href="http://www.exvision.net/miniphp.php" rel="nofollow noreferrer">miniPHP</a> and <a href="http://winbinder.org/" rel="nofollow noreferrer">Winbinder</a>. Is that hidden enough? I guess not many PHP developers have really tried this out.</p>\n'}, {'answer_id': 1092743, 'author': 'Daan', 'author_id': 7922, 'author_profile': 'https://Stackoverflow.com/users/7922', 'pm_score': 2, 'selected': False, 'text': '<h3><a href="http://www.php.net/manual/en/control-structures.alternative-syntax.php" rel="nofollow noreferrer">The alternative syntax for control structures</a></h3>\n\n<p>There are a lot of people who don\'t know this syntax. When I use pure PHP for templating, this syntax offers a nice and clean way to mix simple control structures such as <code>if</code> or <code>foreach</code> with your HTML template code, usually combined with the <code>&lt;?= $myVar ?&gt;</code> short style of printing a variable.</p>\n'}, {'answer_id': 1103508, 'author': 'TheBrain', 'author_id': 130341, 'author_profile': 'https://Stackoverflow.com/users/130341', 'pm_score': 6, 'selected': False, 'text': "<p>You can use <strong>functions with a undefined number of arguments</strong> using the <code>func_get_args()</code>.</p>\n\n<pre><code>&lt;?php\n\nfunction test() {\n\n    $args = func_get_args();\n    echo $args[2]; // will print 'd'\n    echo $args[1]; // will print 3\n}\n\ntest(1,3,'d',4);\n\n?&gt;\n</code></pre>\n"}, {'answer_id': 1141481, 'author': 'RaYell', 'author_id': 137467, 'author_profile': 'https://Stackoverflow.com/users/137467', 'pm_score': 3, 'selected': False, 'text': '<p>Using array elements or object properties inside strings.</p>\n\n<p>Instead of writing</p>\n\n<pre><code>$newVar = $ar[\'foo\'][\'bar\'];\necho "Array value is $newVar";\n\n$newVar = $obj-&gt;foo-&gt;bar;\necho "Object value is $newVar";\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>echo "Array value is {$ar[\'foo\'][\'bar\']}";\necho "Object value is {$obj-&gt;foo-&gt;bar}";\n</code></pre>\n'}, {'answer_id': 1144880, 'author': 'Alex L', 'author_id': 114446, 'author_profile': 'https://Stackoverflow.com/users/114446', 'pm_score': 4, 'selected': False, 'text': '<p><strong><a href="http://us3.php.net/manual/en/ref.ctype.php" rel="nofollow noreferrer">Ctype functions</a> are faster than preg_match() for basic character validation.</strong></p>\n\n<blockquote>\n  <blockquote>\n    <p>ctype_alnum() — Check for alphanumeric character(s)<br>\n    ctype_alpha() — Check for alphabetic character(s)<br>\n    ctype_cntrl() — Check for control character(s)<br>\n    ctype_digit() — Check for numeric character(s)<br>\n    ...etc...</p>\n  </blockquote>\n</blockquote>\n'}, {'answer_id': 1173586, 'author': 'dburke', 'author_id': 72656, 'author_profile': 'https://Stackoverflow.com/users/72656', 'pm_score': 2, 'selected': False, 'text': "<p>I have started to switch over to python, and one thing I loved in python is the live interpreter.  It wasn't until working on a php project later that I realized php does have this option, it's just not widely known.  In a command prompt, type <code>php -a</code> and paste in any php code you want to test, but just remember to start it with <code>&lt;?php</code></p>\n"}, {'answer_id': 1183306, 'author': 'Elzo Valugi', 'author_id': 95353, 'author_profile': 'https://Stackoverflow.com/users/95353', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://es.php.net/manual/en/function.filter-var.php" rel="nofollow noreferrer"><strong>filter_var</strong></a> function. Not a hidden pearl, but pretty new.</p>\n'}, {'answer_id': 1241052, 'author': 'Philippe Gerber', 'author_id': 117260, 'author_profile': 'https://Stackoverflow.com/users/117260', 'pm_score': 7, 'selected': False, 'text': "<p><strong>Include files can have a return value</strong> you can assign to a variable.</p>\n\n<pre><code>// config.php\nreturn array(\n    'db' =&gt; array(\n        'host' =&gt; 'example.org',\n        'user' =&gt; 'usr',\n        // ...\n    ),\n    // ...\n);\n\n// index.php\n$config = include 'config.php';\necho $config['db']['host']; // example.org\n</code></pre>\n"}, {'answer_id': 1295364, 'author': 'Saem', 'author_id': 68131, 'author_profile': 'https://Stackoverflow.com/users/68131', 'pm_score': 2, 'selected': False, 'text': "<p>I suggest using PHPUnit for unit testing, if you want to have annotations for marking your tests, and data providers, and data driven tests, and so on. Not to mention, it seems to get all the integration love when it comes to things like continuous integration (cruise control, bamboo, hudson, etc...).</p>\n\n<p>PHP 5.3, it's a big jump, and it's throughly worth it in terms of language features. It maybe rough around the edges, but this is a startup and they'll be fixed up releases by the time you launch.</p>\n\n<p>As far as magic methods go __invoke() alone is a big deal, but it doesn't have the reciprocal method for it, even then, paired with array_map, array_reduce, and array_filter, and some wrappers you can do some amazing functional programming.</p>\n\n<p>__get, __set, and __call are really handy as well, I used these and some interface/class naming convention trickery to implement traits prior to 5.3, but now you have traits, as well.</p>\n\n<p>Also have a look at the addendum library, written by derik rethans of ezComponents, and XDebug fame, it allows you to do annotations for php 5+. It's not bad, and performance is a non-issue with caching.</p>\n\n<p>For profiling, you can use xdebug + webcachegrind.</p>\n\n<p>The best IDE is probably the free eclipse PDT, if you use type hinting on parameters, and phpdoc comments for parameters and returns it can figure things out from those and provide you code completion. That should give you decent intellisense.</p>\n\n<p>BTW, it's tempting to do all sorts of crazy string concats, or variable variables, or variable method calls, or variable class creation, do this in more than one place, that's not well documented and easy to search via regex, and you're SCREWED. Forget hard to debug, but refactoring is a major pain. This is something people rarely consider php has NO automated refactoring tools, and refactoring large code bases is VERY hard to do in php.</p>\n\n<p>A few things to caution you, even if you smell the slightest bit of possibility that you might have to deal with multi-byte chars, or 'exotic' character encodings, I strongly urge you to wrap up string handling. In fact, introducing a thin layer of indirection which allows you to shim between or act as seams for testing/injectability between your code and built-ins will make your life easier. Not strictly necessary, but unless you have the benefit of foresight, it's hard to tackle internationalization or such large cross-cutting projects.</p>\n\n<p>autoload, learn it and love it. Run away from hard coded require/includes, or worse, their *_once variants, they tie your hands in terms of injection, instead use an autoloader, simplest thing is to jam all your includes in a array, keyed on the class name, and the value is the file path from some root, it's fast. The wicked thing about this is that it makes testing really easy, as you've implemented a class loader, and so you can do some really neat stuff with it.</p>\n\n<p>PHP 5.3 has name spaces now, jump for joy and use them like a mad man. This alone provides an opportunity to create seams (rare) for testing/injections.</p>\n\n<p>Opcode caches, file accesses are slow, to avoid them, use an opcode cache, it's not just the file access, it's all the parsing, really. If you don't have to parse PER request, it makes a BIG difference. Even doing this for a front controller/interceptor will give you a lot of benefits.</p>\n\n<p>Think different, one of the most troubling things for PHP programmers if they come from Java/.Net is that your application server is spread across PHP/Apache, or whatever web server you're using.</p>\n\n<p>Phing/Ant/PHPMaven early on it seems easy just to jam everything in, but build scripts are still useful in php and they have some great support.</p>\n\n<p>I had trouble with method overloading, and still contend with it. I came up with a pattern to alleviate a certain aspect of it. I often had many things that could fulfill a certain parameter, so when you document it @param mixed(int|array|fooObject) if those were the possibilities, I created a static method called Caster::CastTo($param, $toTypeAsString) that would just run through a case matching the type and trying to convert it to a known type. The rest of the method could then assume that one type, or a failure to convert, and work with that. And since I jammed ALL conversions in one class, it stopped mapping of types from being a cross cutting concern, and since these functions can be individually tested, I could test them once, and rely on them everywhere else.</p>\n"}, {'answer_id': 1349122, 'author': 'RedAssBaboon', 'author_id': 140097, 'author_profile': 'https://Stackoverflow.com/users/140097', 'pm_score': 1, 'selected': False, 'text': '<p>In PHP5.3 you can place PHAR archives inside PHAR archives!\nLike WAR/EJB in the java world.</p>\n'}, {'answer_id': 1416447, 'author': 'Kzqai', 'author_id': 69993, 'author_profile': 'https://Stackoverflow.com/users/69993', 'pm_score': 1, 'selected': False, 'text': '<p>My revelations over the years have been more conceptual than language based.</p>\n\n<p>1: Rendering instead of echoing.</p>\n\n<pre><code>function render_title($title){\n     return "&lt;title&gt;$title&lt;/title";\n}\n</code></pre>\n\n<p>so much easier to use the parts repeatably and pass them to templates when you are rendering your output instead of using echos (in which case you\'d have to rely on output buffering).</p>\n\n<p>2: functional programming, or at least as close as I can move towards it, functions without side-effects.  Rendering, not using globals, keeping your functions to having a local scope, things like that.  I thought that object oriented programming was the way to go with php for a while there, but the reduction in overhead and syntax complexity that I experienced from dropping down from object oriented methods to functional programming methods in php makes functional programing the clear choice for me.</p>\n\n<p>3: Templating systems (e.g. smarty).  It\'s taken me a long time to realize that you -need- a templating system inside what is already a template scripting language, but the seperation of logic from display that it gives you is so, so necessary.</p>\n'}, {'answer_id': 1548737, 'author': 'Alex L', 'author_id': 114446, 'author_profile': 'https://Stackoverflow.com/users/114446', 'pm_score': 3, 'selected': False, 'text': '<p>The <a href="http://us.php.net/manual/en/class.reflectionclass.php" rel="noreferrer">ReflectionClass</a> class provides information about a given class.</p>\n\n<pre><code>$classInfo = new ReflectionClass (\'MyClass\');\nif ($classInfo-&gt;hasMethod($methodName))                                     \n{\n  $cm = $classInfo-&gt;getMethod($name);                                   \n  $methodResult = $cm-&gt;invoke(null);\n}\n</code></pre>\n\n<p>Among other things, useful to check if a method exists and call it.</p>\n'}, {'answer_id': 1697712, 'author': 'Frank Koehl', 'author_id': 38358, 'author_profile': 'https://Stackoverflow.com/users/38358', 'pm_score': 3, 'selected': False, 'text': '<p>As others have mentioned, the ability to <strong>run PHP at the command line level</strong> is fantastic. I set PHP scripts as cron jobs for data cleanup and backup purposes all the time. Just start the file with these lines:</p>\n\n<pre><code>#!/usr/bin/php5\n&lt;?php\n// start coding here\n</code></pre>\n\n<p>Note that the first line may be different depending on where PHP is installed on your system.</p>\n\n<p>From here, it\'s easy to implement PHP for more complex system-level processes, <a href="http://www.phpclasses.org/browse/file/8958.html" rel="noreferrer">like daemons</a>.</p>\n'}, {'answer_id': 2022330, 'author': 'ivanjovanovic', 'author_id': 144411, 'author_profile': 'https://Stackoverflow.com/users/144411', 'pm_score': 1, 'selected': False, 'text': '<p>Lot already said about this.</p>\n\n<p>Just to add that one thing that looked pretty forgotten, if not hidden, is <a href="http://talks.php.net" rel="nofollow noreferrer">http://talks.php.net</a> part of the <a href="http://www.php.net" rel="nofollow noreferrer">http://www.php.net</a>. It collects lot of useful presentations, some really old, but some new and extremely valuable.</p>\n'}, {'answer_id': 2032468, 'author': 'Gipetto', 'author_id': 162100, 'author_profile': 'https://Stackoverflow.com/users/162100', 'pm_score': 2, 'selected': False, 'text': '<p>I think that their proper respect for the GOTO function is key.</p>\n\n<p><a href="http://us2.php.net/goto" rel="nofollow noreferrer">http://us2.php.net/goto</a></p>\n'}, {'answer_id': 2032550, 'author': 'Axel Gneiting', 'author_id': 5876, 'author_profile': 'https://Stackoverflow.com/users/5876', 'pm_score': 2, 'selected': False, 'text': '<p>The predefined interfaces:</p>\n\n<p><a href="http://php.net/manual/en/reserved.interfaces.php" rel="nofollow noreferrer">http://php.net/manual/en/reserved.interfaces.php</a></p>\n\n<p>For example implementing <code>ArrayAccess</code> will make your object appear as an array or <code>Iterator</code> will allow it to be used in a foreach statement.</p>\n\n<p>Unfortunately you can\'t use "object arrays" with the native functions that take arrays as parameters.</p>\n\n<p>I also found it useful to override the <code>__call</code> function which allows you to dynamically create properties and methods for an object. </p>\n\n<p>In my database abstraction I use this to generate functions that are named by the database column names. For example if there is a column \'name\' then you can change values in it by using <code>updateByName("foo")</code>.</p>\n'}, {'answer_id': 2116251, 'author': 'RJD22', 'author_id': 255920, 'author_profile': 'https://Stackoverflow.com/users/255920', 'pm_score': 0, 'selected': False, 'text': '<p>Another nice feature is <a href="http://php.net/manual/en/function.copy.php" rel="nofollow noreferrer">copy()</a>. This function makes it possible to get a file from any place(even urls work) and copy it to a local resource. So grabbing files becomes really easy.</p>\n'}, {'answer_id': 2134782, 'author': 'Alexandru Mos', 'author_id': 226472, 'author_profile': 'https://Stackoverflow.com/users/226472', 'pm_score': 0, 'selected': False, 'text': '<p>Magic method <strong>__callStatic</strong>.</p>\n\n<p>Really useful to make singletons, like this <a href="http://www.php.net/manual/en/book.pdo.php#93178" rel="nofollow noreferrer">PDO singleton class</a></p>\n'}, {'answer_id': 2136385, 'author': 'Peter', 'author_id': 227491, 'author_profile': 'https://Stackoverflow.com/users/227491', 'pm_score': 0, 'selected': False, 'text': '<p>Question about the original post: Why do you need a switch statement in order to overload a method in PHP? Maybe you mean something by the term "overload" that doesn\'t match what I learned from C++.</p>\n\n<p>As for favorite features of PHP, I like the Exception object. I find that having a standard error container makes it much easier to decouple the presentation logic from the business logic, and the throw/catch syntax makes it much easier to write automated tests for each class in isolation.</p>\n'}, {'answer_id': 2161431, 'author': 'Talvi Watia', 'author_id': 215170, 'author_profile': 'https://Stackoverflow.com/users/215170', 'pm_score': 1, 'selected': False, 'text': "<p><strong>Stackable unit files</strong></p>\n\n<pre><code>&lt;?\n// file unit1.php\n$this_code='does something.';\n?&gt;\n\n&lt;?\n// file unit2.php\n$this_code='does something else. it could be a PHP class object!';\n?&gt;\n\n&lt;?\n// file unit3.php\n$this_code='does something else. it could be your master include file';\nrequire_once('unit2.php');\ninclude('unit1.php');\n?&gt;\n\n&lt;?\n// file main.php\ninclude('unit1.php');\nrequire_once('unit2.php');\nrequire_once('unit3.php');\n?&gt;\n</code></pre>\n\n<p>I purposely used include and require_once interchangeably to show what can be done, because they work differently.</p>\n\n<p>There are multiple ways to construct your code or add files into your code. It is even possible to link HTML, AJAX, CSS, JAVASCRIPT, IMAGES and all sorts of files into your code dynamically. </p>\n\n<p>I especially like it, because there are also no requirements of placing the includes/requires at the beginning, middle or end. This allows for more freedom, depending on the use. </p>\n"}, {'answer_id': 2321536, 'author': 'GreenMatt', 'author_id': 197011, 'author_profile': 'https://Stackoverflow.com/users/197011', 'pm_score': 0, 'selected': False, 'text': '<p>Using <a href="http://us.php.net/manual/en/book.curl.php" rel="nofollow noreferrer">cURL</a> to set up a test suite to drive a large, complex web form and its back end application.  The tests were exhaustive - at least in terms of executing every combination of acceptable inputs.</p>\n'}, {'answer_id': 3089775, 'author': 'bob-the-destroyer', 'author_id': 352583, 'author_profile': 'https://Stackoverflow.com/users/352583', 'pm_score': 3, 'selected': False, 'text': "<p>Just about any file type can be <code>included</code>, from .html to .jpeg.  Any byte string found inside bound by PHP open tags will be executed.  Yes, an image of goat.se can contain all your usual utility functions.  I'm guessing the internal behavior of <code>include</code> is to convert the input file to string, and parse for any php code.</p>\n"}, {'answer_id': 3111088, 'author': 'manixrock', 'author_id': 93691, 'author_profile': 'https://Stackoverflow.com/users/93691', 'pm_score': 4, 'selected': False, 'text': '<p>You can use <code>break <em>N</em>;</code> to exit nested loops (to compensate for the lack of <code>goto</code>). For example</p>\n\n<pre><code>for (int i=0; i&lt;100; i++) {\n    foreach ($myarr as $item) {\n        if ($item[\'name\'] == \'abort\')\n            break 2;\n    }\n}\n</code></pre>\n\n<p>More info here - <a href="http://php.net/manual/en/control-structures.break.php" rel="nofollow noreferrer">http://php.net/manual/en/control-structures.break.php</a></p>\n'}, {'answer_id': 3135918, 'author': 'fixo2020 ', 'author_id': 347194, 'author_profile': 'https://Stackoverflow.com/users/347194', 'pm_score': -1, 'selected': False, 'text': '<p>You can set a check on every option when use switch statement, this is an example:</p>\n\n<pre><code>$check = "HELLO";\n\nswitch ($check) {\n       case (eregi(\'HI\', $check)):\n             echo "Write HI!";\n       case (eregi(\'HELLO\', $check)):\n             echo "Write HELLO!";\n       case (eregi(\'OTHER\', $check)):\n             echo "Write OTHER!";\n}\n</code></pre>\n\n<p>Bye...</p>\n'}, {'answer_id': 3136088, 'author': 'Codler', 'author_id': 304894, 'author_profile': 'https://Stackoverflow.com/users/304894', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Lambda functions</strong></p>\n\n<p>Example - sort by field in multidimension-array</p>\n\n<pre><code>function sort_by_field($field, &amp; $data) {\n    $sort_func = create_function(\'$a,$b\', \'if ($a["\' . $field . \'"] == $b["\' . $field . \'"]) {return 0;} \n            return ($a["\' . $field . \'"] &lt; $b["\' . $field . \'"]) ? -1 : 1;\');\n\n    uasort($data, $sort_func);\n}\n</code></pre>\n\n<p><strong>Anonymous functions</strong></p>\n\n<p>Anonymous functions lets you define a function to a variable.\n<a href="http://www.php.net/manual/en/functions.anonymous.php" rel="nofollow noreferrer">http://www.php.net/manual/en/functions.anonymous.php</a></p>\n'}, {'answer_id': 3136831, 'author': 'Xeoncross', 'author_id': 99923, 'author_profile': 'https://Stackoverflow.com/users/99923', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Shorthand Boolean Chains</strong></p>\n\n<pre><code>&lt;?php\n\nTRUE AND print \'Hello\';\nFALSE OR print \'World\';\n\n// Prints "Hello World";\n\n// Complex example...\nUser::logged_in() or die(\'Not allowed\');\nUser::is_admin() AND print \'Admin Area\';\n</code></pre>\n\n<p>Which is really useful if you have PHP files in a web-accessable area. By inserting this little tidbit at the top of each file you can make sure that no-one can access any file but index.php</p>\n\n<pre><code>&lt;?php defined(\'YOURCONSTANT\') or die(\'Not allowed\');\n\n///rest of your code\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/61401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']