Saturday, 29 October 2016

10 Amazing apps you should download Right now

In this IOS world, there are thousands of Apps that can be useful enough  but still there are some apps that you should Download Right now, as because there are some Reasons that may encourage you download all of them in your iphone.

1.Whatsapp


Yes! WhatsApp don't you heard that this app is FREE now to download for IOS users. It's uses your Wifi network (yes Internet connection such as 4g,3g,2g) and to call your friends and message them for free. Send your favourite pictures,videos,(nowadays GIFs) and voice messages with Other 900 WhatsApp Users.

2.Instagram


One of the most Famous app in mobile world where you can filter your photos and share them with your beloved. And then you can Follow Other Users to see their Filtered Pictures too.

3.Uber


Uber - the controversial taxi app - makes getting around easier. Rather than having to call for a cab with cash in your wallet, you can request it and pay for it through the app. In the UK, Uber currently operates in London, Leeds, Manchester, Sheffield, Bristol, Birmingham and Newcastle.

4.CityMapper




Do you Know, The best way to navigate yourself across any city, well for that purpose cityMapper can help you,This app includes the A to B  journey  Planner  real-time traffic data, public transport delays, and map.

5.DropBox


Wanna Backup all your photos,documents and many other files and then in future want to access them from anywhere in any device, Dropbox's IOS app is for you. It can also be useful for sending files as well as other documents without any Email atachments.

6.Shazam


Its an iOS staple since 2008 - will tell you the name and artist of any song within seconds. It will also pull up YouTube videos, give you lyrics and let you add the song to your Rdio or Spotify playlists. Use it to discover new music too with its recommended tracks.

7.Candy Crush Saga


Candy Crush Saga is a hugely addictive puzzle game that lets you move through the levels by matching combinations of coloured sweets. The free to play game was one of the top 10 iOS downloads last year - despite launching in November 2012.

8.Facebook Messenger


Facebook's standalone messaging app has over 800 million active users. It's continuing to add new features - taking it beyond a mere chat app. Most recently, it's added Uber integration, video calling and the artificially intelligent assistant 'M' (currently only available to select users).
 
9.AirBnb



Airbnb is a must have app for anyone who likes to travel. Browse places to stay in over 34,000 cities, communicate with hosts, get directions, and pay for your room through the app. Hosts can also manage their listings through the app.

10.Spotify


Spotify is a music streaming app that gives you access to a library of over 30 million tracks. There's a free version with ads, or a £9.99-per-month option that lets you play any song at any time and save music so it's available offline.



Friday, 28 October 2016

Why “C” Is The Default Drive On Your Computer & Not A Or B? Here is Your Answer

A long time ago it was difficult to have a personal computer. Working with a computer was this kind of deluxe nobody could potentially purchase. But, in today’s world the amount of computers owners are increased drastically than it was thought by the creators. and have you checked out ? it’s the most crucial machine these days. Right now of Tech world, it’s not surprising if anybody says that computer is the central element of a human.
Even though you may be utilizing the pc for several days, most likely there would be a lot of things that have been unfamiliar to you. If you work with the computer for many days, then listed here is a concern for you.


In Windows, Why C Drive is Default? Here is the Answer

Hard disk drives turned into standard since 1980. Earlier hard disk drives, Floppy disk drives were utilized as the storage devices. Floppy disk drives were the first storage devices. They came to existence since 1960’s. Floppy disks was available in two sizes 5 1/4 ” and 3 1/2″. Those two floppy disk drives were labelled as Local Disk (A) and Local Disk (B). After the innovation of Hard disk, floppy disk of size 8 inch was introduced. Currently Floppy disk drives and Floppy disk drives changed the floppy disks.

That’s why at the rear of the labelling of hard drives. Consequently, drives besides default drive (C) labelled as D, E etc. DVD drive and USB drive are labelled as F, G and so forth.
Still “C” drive is available as the standard, you are able to change it to A or B if you’ve got the administrative rights.
Now you know Why is C the Default Hard Drive Of Your Computer!
If you attach too many drives and all letters till Z are assigned, then if there is no more drive letter is free to assign, then whatever next drive you connect it won’t be shown in Windows OS.

Sunday, 2 October 2016

Top ten errors Java Programmers make

    Top ten errors Java Programmers make

        (We will learn How to Spot them and fix them.) 



Whether you program regularly in Java, and know it like the back of your hand, or whether you're new to the language or a casual programmer, you'll make mistakes. It's natural, it's human, and guess what? You'll more than likely make the same mistakes that others do, over and over again. Here's my top ten list of errors that we all seem to make at one time or another,  how to spot them, and how to fix them.

10. Accessing non-static member variables from static methods (such as main)

Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don't need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-
MyApplication.main ( command_line_args );
This means, however, that there isn't an instance of MyApplication - it doesn't have any member variables to access! Take for example the following application, which will generate a compiler error message.
public class StaticDemo
{
        public String my_member_variable = "somedata";
        public static void main (String args[])
        {
  // Access a non-static member from static method
                System.out.println ("This generates a compiler error" +
   my_member_variable );
        }
}
If you want to access its member variables from a non-static method (likemain), you must create an instance of the object. Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.
public class NonStaticDemo
{
        public String my_member_variable = "somedata";

        public static void main (String args[])
        {
                NonStaticDemo demo = new NonStaticDemo();

  // Access member variable of demo
                System.out.println ("This WON'T generate an error" +
                        demo.my_member_variable );
        }
}

9. Mistyping the name of a method when overriding

Overriding allows programmers to replace a method's implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you'll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.
public class MyWindowListener extends WindowAdapter {
 // This should be WindowClosed
 public void WindowClose(WindowEvent e) {
  // Exit when user closes window
  System.exit(0);
 }
});
Compilers won't pick up on this one, and the problem can be quite frustrating to detect. In the past, I've looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn't being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn't being called, then it's likely you've mistyped the name.

8. Comparison assignment (  = rather than == )

This is an easy error to make. If you're used other languages before, such as Pascal, you'll realize just how poor a choice this was by the language's designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.
Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.
Here's the correct way to compare two strings.
String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
{
    ......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
   .....
}

6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.
When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.
When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type.  So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.
On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

5. Writing blank exception handlers

I know it's very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven't written any error messages, it becomes almost impossible to find out the cause of the error. Even the simplest exception handler can be of benefit. For example, put a try { .. } catch Exception around your code, to catch ANY type of exception, and print out the message. You don't need to write a custom handler for every exception (though this is still good programming practice). Don't ever leave it blank, or you won't know what's happening.
For example
public static void main(String args[])
{
    try {
 // Your code goes here..
    }
    catch (Exception e)
    {
 System.out.println ("Err - " + e );
    }
}

4. Forgetting that Java is zero-indexed

If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0. Confused? Let's look at a quick example.
// Create an array of three strings
String[] strArray = new String[3];

// First element's index is actually 0
strArray[0] = "First string";

// Second element's index is actually 1
strArray[1] = "Second string";

// Final element's index is actually 2
strArray[2] = "Third and final string";
In this example, we have an array of three strings, but to access elements of the array we actually subtract one. Now, if we were to try and access strArray[3], we'd be accessing the fourth element. This will case an ArrayOutOfBoundsException to be thrown - the most obvious sign of forgetting the zero-indexing rule.
Other areas where zero-indexing can get you into trouble is with strings. Suppose you wanted to get a character at a particular offset within a string. Using the String.charAt(int) function you can look this information up - but under Java, the String class is also zero-indexed. That means than the first character is at offset 0, and second at offset 1. You can run into some very frustrating problems unless you are aware of this - particularly if you write applications with heavy string processing. You can be working on the wrong character, and also throw exceptions at run-time. Just like the ArrayOutOfBoundsException, there is a string equivalent. Accessing beyond the bounds of a String will cause a StringIndexOutOfBoundsException to be thrown, as demonstrated by this example.
public class StrDemo
{
 public static void main (String args[])
 {
        String abc = "abc";

        System.out.println ("Char at offset 0 : " + abc.charAt(0) );
        System.out.println ("Char at offset 1 : " + abc.charAt(1) );
        System.out.println ("Char at offset 2 : " + abc.charAt(2) );

 // This line should throw a StringIndexOutOfBoundsException
        System.out.println ("Char at offset 3 : " + abc.charAt(3) );
 }
}
Note too, that zero-indexing doesn't just apply to arrays, or to Strings. Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application.
import java.util.Date;
import java.util.Calendar;

public class ZeroIndexedDate
{
        public static void main (String args[])
        {
                // Get today's date
                Date today = new Date();
 
  // Print return value of getMonth
  System.out.println ("Date.getMonth() returns : " +
    today.getMonth());

  // Get today's date using a Calendar
  Calendar rightNow = Calendar.getInstance();

  // Print return value of get ( Calendar.MONTH )
  System.out.println ("Calendar.get (month) returns : " +
   rightNow.get ( Calendar.MONTH ));
        }
}
Zero-indexing is only a problem if you don't realize that its occurring. If you think you're running into a problem, always consult your API documentation.

3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.
Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.
How can this problem be solved? The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.
public class MyCounter
{
 private int count = 0; // count starts at zero

 public synchronized void setCount(int amount)
 { 
  count = amount;
 }
 
 public synchronized int getCount()
 {
  return count;
 }
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don't spot the lack of capitalization.
While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-
  • all methods and member variables in the Java API begin with lowercase letters
  • all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()
If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you'll make. It may take a while, but it can save some serious head scratching in the future.

(drum roll)

And the number one error that Java programmers make !!!!!


1. Null pointers!

Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.
When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.
Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!
Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.
public static void main(String args[])
{
 // Accept up to 3 parameters
 String[] list = new String[3];

 int index = 0;

 while ( (index < args.length) && ( index < 3 ) )
 {
  list[index++] = args[index];
 }

 // Check all the parameters 
 for (int i = 0; i < list.length; i++)
 {
  if (list[i].equals "-help")
  {
   // .........
  }
  else
  if (list[i].equals "-cp")
  {
   // .........
  }
  // else .....
 } 
}
This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Summary

These errors represent but some of the many that we all make. Though it is impossible to completely eliminate errors from the coding process, with care and practice you can avoid repeating the same ones. Rest assured, however, that all Java programmers encounter the same sorts of problems. It's comforting to know, that while you work late into the night tracking down an error, someone, somewhere, sometime, will make the same mistake!
We'd like to thank the readers of the comp.lang.java.programmer newsgroup for their suggestions for the top ten. Regrettably, due to the number of submissions, not every error could be featured - but we think this "Top Ten" list represents the most popular and frequent errors people make.

Simple Programming errors to Learn and Solve

                                                           taken by :cprogramming

1. Undeclared Variables

int main()
{
  cin>>x;
  cout<<x;
}
"Huh? Why do I get an error?" 

Your compiler doesn't know what x means. You need to declare it as a variable.
int main()
{
  int x;
  cin>>x;
  cout<<x;
}

2. Uninitialized variables

int count;
while(count<100)
{
  cout<<count;
  count++;
}
"Why doesn't my program enter the while loop?" 

In C++ variables are not initialized to zero. In the above snippet of code, count could be any value in the range of int. It might, for example, be 586, and in that situation the while loop's condition would never be true. Perhaps the output of the program would be to print the numbers from -1000 to 99. In that case, once again, the variable was assigned a memory location with garbage data that happened to evaluate to -1000. 

Remember to initialize your variables.

3. Setting a variable to an uninitialized value

int a, b;
int sum=a+b;
cout<<"Enter two numbers to add: ";
cin>>a;
cin>>b;
cout<<"The sum is: "<<sum;
When Run:
Enter two numbers to add: 1 3
The sum is: -1393
"What's wrong with my program?" 

Often beginning programmers believe that variables work like equations - if you assign a variable to equal the result of an operation on several other variables that whenever those variables change (a and b in this example), the value of the variable will change. In C++ assignment does not work this way: it's a one shot deal. Once you assign a value to a variable, it's that value until you reassign the values. In the example program, because a and b are not initialized, sum will equal an unknown random number, no matter what the user inputs. 

To fix this error, move the addition step after the input line.
int a, b;
int sum;
cout<<"Enter two numbers to add: ";
cin>>b;
cin>>a;
sum=a+b;
cout<<"The sum is: "<<sum;

4. Using a single equal sign to check equality

char x='Y';
while(x='Y')
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}
"Why doesn't my loop ever end?" 

If you use a single equal sign to check equality, your program will instead assign the value on the right side of the expression to the variable on the left hand side, and the result of this statement is the value assigned. In this case, the value is 'Y', which is treated as true. Therefore, the loop will never end. Use == to check for equality; furthermore, to avoid accidental assignment, put variables on the right hand side of the expression and you'll get a compiler error if you accidentally use a single equal sign as you can't assign a value to something that isn't a variable.
char x='Y';
while('Y'==x)
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}

5. Undeclared Functions

int main()
{
  menu();
}
void menu()
{
  //...
}
"Why do I get an error about menu being unknown?" 

The compiler doesn't know what menu() stands for until you've told it, and if you wait until after using it to tell it that there's a function named menu, it will get confused. Always remember to put either a prototype for the function or the entire definition of the function above the first time you use the function.
void menu();
int main()
{
  menu();
}
void menu()
{
  ...
}

6. Extra Semicolons

int x;
for(x=0; x<100; x++);
  cout<<x;
"Why does it output 100?" 

You put in an extra semicolon. Remember, semicolons don't go after if statements, loops, or function definitions. If you put one in any of those places, your program will function improperly.
int x;
for(x=0; x<100; x++)
  cout<<x;

7. Overstepping array boundaries

int array[10];
//...
for(int x=1; x<=10; x++)
  cout<<array[x];
"Why doesn't it output the correct values?" 

Arrays begin indexing at 0; they end indexing at length-1. For example, if you have a ten element array, the first element is at position zero and the last element is at position 9.
int array[10];
//...
for(int x=0; x<10; x++)
  cout<<array[x];

8. Misusing the && and || operators

int value;
do
{
  //...
  value=10;
}while(!(value==10) || !(value==20))
"Huh? Even though value is 10 the program loops. Why?" 

Consider the only time the while loop condition could be false: both value==10 and value==20 would have to be true so that the negation of each would be false in order to make the || operation return false. In fact, the statement given above is a tautology; it is always true that value is not equal to 10 or not equal to 20 as it can't be both values at once. Yet, if the intention is for the program only to loop if value has neither the value of ten nor the value of 20, it is necessary to use && : !(value==10) && !(value==20), which reads much more nicely: "if value is not equal to 10 and value is not equal to 20", which means if value is some number other than ten or twenty (and therein is the mistake the programmer makes - he reads that it is when it is "this" or "that", when he forgets that the "other than" applies to the entire statement "ten or twenty" and not to the two terms - "ten", "twenty" - individually). A quick bit of boolean algebra will help you immensely: !(A || B) is the equivalent of !A && !B (Try it and see; you can read more about this rule on Wikipedia: DeMorgan's Law). The sentence "value is other than [ten or twenty]" (brackets added to show grouping) is translatable to !(value==10 || value==20), and when you distribute the !, it becomes !(value==10) && !(value==20). 

The proper way to rewrite the program:
int value;
do
{
  //...
  value=10;
}while(!(value==10) && !(value==20))

Error you should be aware of in PHP made commonly

PHP makes it relatively easy to build a web-based system, which is much of the reason for its popularity. But its ease of use notwithstanding, PHP has evolved into quite a sophisticated language with many frameworks, nuances, and subtleties that can bite developers, leading to hours of hair-pulling debugging. This article highlights ten of the more common mistakes that PHP developers need to beware of.

Common Mistake #1: Leaving dangling array references after foreach loops

Not sure how to use foreach loops in PHP? Using references in foreach loops can be useful if you want to operate on each element in the array that you are iterating over. For example:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
The problem is that, if you’re not careful, this can also have some undesirable side effects and consequences. Specifically, in the above example, after the code is executed, $value will remain in scope and will hold a reference to the last element in the array. Subsequent operations involving $value could therefore unintentionally end up modifying the last element in the array.
The main thing to remember is that foreach does not create a scope. Thus, $value in the above example is a reference within the top scope of the script. On each iteration foreach sets the reference to point to the next element of $array. After the loop completes, therefore, $value still points to the last element of $array and remains in scope.
Here’s an example of the kind of evasive and confusing bugs that this can lead to:
$array = [1, 2, 3];
echo implode(',', $array), "\n";

foreach ($array as &$value) {}    // by reference
echo implode(',', $array), "\n";

foreach ($array as $value) {}     // by value (i.e., copy)
echo implode(',', $array), "\n";
The above code will output the following:
1,2,3
1,2,3
1,2,2
No, that’s not a typo. The last value on the last line is indeed a 2, not a 3.
Why?
After going through the first foreach loop, $array remains unchanged but, as explained above, $value is left as a dangling reference to the last element in $array (since that foreach loop accessed $value by reference).
As a result, when we go through the second foreach loop, “weird stuff” appears to happen. Specifically, since $value is now being accessed by value (i.e., by copy), foreach copies each sequential $array element into $value in each step of the loop. As a result, here’s what happens during each step of the second foreach loop:
  • Pass 1: Copies $array[0] (i.e., “1”) into $value (which is a reference to $array[2]), so $array[2] now equals 1. So $array now contains [1, 2, 1].
  • Pass 2: Copies $array[1] (i.e., “2”) into $value (which is a reference to $array[2]), so $array[2] now equals 2. So $array now contains [1, 2, 2].
  • Pass 3: Copies $array[2] (which now equals “2”) into $value (which is a reference to $array[2]), so $array[2] still equals 2. So $array now contains [1, 2, 2].
To still get the benefit of using references in foreach loops without running the risk of these kinds of problems, call unset() on the variable, immediately after the foreach loop, to remove the reference; e.g.:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
unset($value);   // $value no longer references $arr[3]

Common Mistake #2: Misunderstanding isset() behavior

Despite its name, isset() not only returns false if an item does not exist, but also returns false for null values.
This behavior is more problematic than it might appear at first and is a common source of problems.
Consider the following:
$data = fetchRecordFromStorage($storage, $identifier);
if (!isset($data['keyShouldBeSet']) {
    // do something here if 'keyShouldBeSet' is not set
}
The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data['keyShouldBeSet']) will also return false if $data['keyShouldBeSet'] was set, but was set to null. So the above logic is flawed.
Here’s another example:
if ($_POST['active']) {
    $postData = extractSomething($_POST);
}

// ...

if (!isset($postData)) {
    echo 'post not active';
}
The above code assumes that if $_POST['active'] returns true, then postData will necessarily be set, and therefore isset($postData) will return true. So conversely, the above code assumes that the only way that isset($postData) will return false is if $_POST['active'] returned false as well.
Not.
As explained, isset($postData) will also return false if $postData was set to null. It therefore is possible for isset($postData) to return false even if $_POST['active'] returned true. So again, the above logic is flawed.
And by the way, as a side point, if the intent in the above code really was to again check if $_POST['active'] returned true, relying on isset() for this was a poor coding decision in any case. Instead, it would have been better to just recheck $_POST['active']; i.e.:
if ($_POST['active']) {
    $postData = extractSomething($_POST);
}

// ...

if ($_POST['active']) {
    echo 'post not active';
}
For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to null), the array_key_exists() method is a much more robust solution.
For example, we could rewrite the first of the above two examples as follows:
$data = fetchRecordFromStorage($storage, $identifier);
if (! array_key_exists('keyShouldBeSet', $data)) {
    // do this if 'keyShouldBeSet' isn't set
}
Moreover, by combining array_key_exists() with get_defined_vars(), we can reliably check whether a variable within the current scope has been set or not:
if (array_key_exists('varShouldBeSet', get_defined_vars())) {
    // variable $varShouldBeSet exists in current scope
}

Common Mistake #3: Confusion about returning by reference vs. by value

Consider this code snippet:
class Config
{
    private $values = [];

    public function getValues() {
        return $this->values;
    }
}

$config = new Config();

$config->getValues()['test'] = 'test';
echo $config->getValues()['test'];
If you run the above code, you’ll get the following:
PHP Notice:  Undefined index: test in /path/to/my/script.php on line 21
What’s wrong?
The issue is that the above code confuses returning arrays by reference with returning arrays by value. Unless you explicitly tell PHP to return an array by reference (i.e., by using&), PHP will by default return the the array “by value”. This means that a copy of the array will be returned and therefore the called function and the caller will not be accessing the same instance of the array.
So the above call to getValues() returns a copy of the $values array rather than a reference to it. With that in mind, let’s revisit the two key lines from the above the example:
// getValues() returns a COPY of the $values array, so this adds a 'test' element
// to a COPY of the $values array, but not to the $values array itself.
$config->getValues()['test'] = 'test';

// getValues() again returns ANOTHER COPY of the $values array, and THIS copy doesn't
// contain a 'test' element (which is why we get the "undefined index" message).
echo $config->getValues()['test'];
One possible fix would be to save the first copy of the $values array returned by getValues() and then operate on that copy subsequently; e.g.:
$vals = $config->getValues();
$vals['test'] = 'test';
echo $vals['test'];
That code will work fine (i.e., it will output test without generating any “undefined index” message), but depending on what you’re trying to accomplish, this approach may or may not be adequate. In particular, the above code will not modify the original $values array. So if you do want your modifications (such as adding a ‘test’ element) to affect the original array, you would instead need to modify the getValues() function to return a reference to the $values array itself. This is done by adding a & before the function name, thereby indicating that it should return a reference; i.e.:
class Config
{
    private $values = [];

    // return a REFERENCE to the actual $values array
    public function &getValues() {
        return $this->values;
    }
}

$config = new Config();

$config->getValues()['test'] = 'test';
echo $config->getValues()['test'];
The output of this will be test, as expected.
But to make things more confusing, consider instead the following code snippet:
class Config
{
    private $values;

    // using ArrayObject rather than array
    public function __construct() {
        $this->values = new ArrayObject();
    }

    public function getValues() {
        return $this->values;
    }
}

$config = new Config();

$config->getValues()['test'] = 'test';
echo $config->getValues()['test'];
If you guessed that this would result in the same “undefined index” error as our earlier array example, you were wrong. In fact, this code will work just fine. The reason is that, unlike arrays, PHP always passes objects by reference. (ArrayObject is an SPL object, which fully mimics arrays usage, but works as an object.)
As these examples demonstrate, it is not always entirely obvious in PHP whether you are dealing with a copy or a reference. It is therefore essential to understand these default behaviors (i.e., variables and arrays are passed by value; objects are passed by reference) and also to carefully check the API documentation for the function you are calling to see if it is returning a value, a copy of an array, a reference to an array, or a reference to an object.
All that said, it is important to note that the practice of returning a reference to an array or an ArrayObject is generally something that should be avoided, as it provides the caller with the ability to modify the instance’s private data. This “flies in the face” of encapsulation. Instead, it’s better to use old style “getters” and “setters”, e.g.:
class Config
{
    private $values = [];
    
    public function setValue($key, $value) {
        $this->values[$key] = $value;
    }
    
    public function getValue($key) {
        return $this->values[$key];
    }
}

$config = new Config();

$config->setValue('testKey', 'testValue');
echo $config->getValue('testKey');    // echos 'testValue'
This approach gives the caller the ability to set or get any value in the array without providing public access to the otherwise-private $values array itself.

Common Mistake #4: Performing queries in a loop

It’s not uncommon to come across something like this if your PHP is not working:
$models = [];

foreach ($inputValues as $inputValue) {
    $models[] = $valueRepository->findByValue($inputValue);
}
While there may be absolutely nothing wrong here, but if you follow the logic in the code, you may find that the innocent looking call above to $valueRepository->findByValue() ultimately results in a query of some sort, such as:
$result = $connection->query("SELECT `x`,`y` FROM `values` WHERE `value`=" . $inputValue);
As a result, each iteration of the above loop would result in a separate query to the database. So if, for example, you supplied an array of 1,000 values to the loop, it would generate 1,000 separate queries to the resource! If such a script is called in multiple threads, it could potentially bring the system to a grinding halt.
It’s therefore crucial to recognize when queries are being made by your code and, whenever possible, gather the values and then run one query to fetch all the results.
One example of a fairly common place to encounter querying being done inefficiently (i.e., in a loop) is when a form is posted with a list of values (IDs, for example). Then, to retrieve the full record data for each of the IDs, the code will loop through the array and do a separate SQL query for each ID. This will often look something like this:
$data = [];
foreach ($ids as $id) {
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = " . $id);
    $data[] = $result->fetch_row();
}
But the same thing can be accomplished much more efficiently in a single SQL query as follows:
$data = [];
if (count($ids)) {
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (" . implode(',', $ids));
    while ($row = $result->fetch_row()) {
        $data[] = $row;
    }
}
It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake…

Common Mistake #5: Memory usage headfakes and inefficiencies

While fetching many records at once is definitely more efficient than running a single query for each row to fetch, such an approach can potentially lead to an “out of memory” condition in libmysqlclient when using PHP’s mysql extension.
To demonstrate, let’s take a look at a test box with limited resources (512MB RAM), MySQL, and php-cli.
We’ll bootstrap a database table like this:
// connect to mysql
$connection = new mysqli('localhost', 'username', 'password', 'database');

// create table of 400 columns
$query = 'CREATE TABLE `test`(`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT';
for ($col = 0; $col < 400; $col++) {
    $query .= ", `col$col` CHAR(10) NOT NULL";
}
$query .= ');';
$connection->query($query);

// write 2 million rows
for ($row = 0; $row < 2000000; $row++) {
    $query = "INSERT INTO `test` VALUES ($row";
    for ($col = 0; $col < 400; $col++) {
        $query .= ', ' . mt_rand(1000000000, 9999999999);
    }
    $query .= ')';
    $connection->query($query);
}
OK, now let’s check resources usage:
// connect to mysql
$connection = new mysqli('localhost', 'username', 'password', 'database');
echo "Before: " . memory_get_peak_usage() . "\n";

$res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 1');
echo "Limit 1: " . memory_get_peak_usage() . "\n";

$res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 10000');
echo "Limit 10000: " . memory_get_peak_usage() . "\n";
Output:
Before: 224704
Limit 1: 224704
Limit 10000: 224704
Cool. Looks like the query is safely managed internally in terms of resources.
Just to be sure, though, let’s boost the limit one more time and set it to 100,000. Uh-oh. When we do that, we get:
PHP Warning:  mysqli::query(): (HY000/2013):
              Lost connection to MySQL server during query in /root/test.php on line 11
What happened?
The issue here is the way PHP’s mysql module works. It’s really just a proxy for libmysqlclient, which does the dirty work. When a portion of data is selected, it goes directly into memory. Since this memory is not managed by PHP’s manager, memory_get_peak_usage() won’t show any increase in resources utilization as we up the limit in our query. This leads to problems like the one demonstrated above where we’re tricked into complacency thinking that our memory management is fine. But in reality, our memory management is seriously flawed and we can experience problems like the one shown above.
You can at least avoid the above headfake (although it won’t itself improve your memory utilization) by instead using the mysqlnd module. mysqlnd is compiled as a native PHP extension and it does use PHP’s memory manager.
Therefore, if we run the above test using mysqlnd rather than mysql, we get a much more realistic picture of our memory utilization:
Before: 232048
Limit 1: 324952
Limit 10000: 32572912
And it’s even worse than that, by the way. According to PHP documentation, mysql uses twice as many resources as mysqlnd to store data, so the original script using mysql really used even more memory than shown here (roughly twice as much).
To avoid such problems, consider limiting the size of your queries and using a loop with small number of iterations; e.g.:
$totalNumberToFetch = 10000;
$portionSize = 100;

for ($i = 0; $i <= ceil($totalNumberToFetch / $portionSize); $i++) {
    $limitFrom = $portionSize * $i;
    $res = $connection->query(
                         "SELECT `x`,`y` FROM `test` LIMIT $limitFrom, $portionSize");
}
When we consider both this PHP mistake and mistake #4 above, we realize that there is a healthy balance that your code ideally needs to achieve between, on the one hand, having your queries being too granular and repetitive, vs. having each of your individual queries be too large. As is true with most things in life, balance is needed; either extreme is not good and can cause problems with PHP not working properly.

Common Mistake #6: Ignoring Unicode/UTF-8 issues

In some sense, this is really more of an issue in PHP itself than something you would run into while debugging PHP, but it has never been adequately addressed. PHP 6’s core was to be made Unicode-aware, but that was put on hold when development of PHP 6 was suspended back in 2010.
But that by no means absolves the developer from properly handing UTF-8 and avoiding the erroneous assumption that all strings will necessarily be “plain old ASCII”. Code that fails to properly handle non-ASCII strings is notorious for introducing gnarly heisenbugs into your code. Even simple strlen($_POST['name']) calls could cause problems if someone with a last name like “Schrödinger” tried to sign up into your system.
Here’s a small checklist to avoid such problems in your code:
  • If you don’t know much about Unicode and UTF-8, you should at least learn the basics. There’s a great primer here.
  • Be sure to always use the mb_* functions instead of the old string functions (make sure the “multibyte” extension is included in your PHP build).
  • Make sure your database and tables are set to use Unicode (many builds of MySQL still use latin1 by default).
  • Remember that json_encode() converts non-ASCII symbols (e.g., “Schrödinger” becomes “Schr\u00f6dinger”) but serialize() does not.
  • Make sure your PHP code files are also UTF-8 encoded to avoid collisions when concatenating strings with hardcoded or configured string constants.
A particularly valuable resource in this regard is the UTF-8 Primer for PHP and MySQL post by Francisco Claria on this blog.

Common Mistake #7: Assuming $_POST will always contain your POST data

Despite its name, the $_POST array won’t always contain your POST data and can be easily found empty. To understand this, let’s take a look at an example. Assume we make a server request with a jQuery.ajax() call as follows:
// js
$.ajax({
    url: 'http://my.site/some/path',
    method: 'post',
    data: JSON.stringify({a: 'a', b: 'b'}),
    contentType: 'application/json'
});
(Incidentally, note the contentType: 'application/json' here. We send data as JSON, which is quite popular for APIs. It’s the default, for example, for posting in theAngularJS $http service.)
On the server side of our example, we simply dump the $_POST array:
// php
var_dump($_POST);
Surprisingly, the result will be:
array(0) { }
Why? What happened to our JSON string {a: 'a', b: 'b'}?
The answer is that PHP only parses a POST payload automatically when it has a content type of application/x-www-form-urlencoded or multipart/form-data. The reasons for this are historical — these two content types were essentially the only ones used years ago when PHP’s $_POST was implemented. So with any other content type (even those that are quite popular today, like application/json), PHP doesn’t automatically load the POST payload.
Since $_POST is a superglobal, if we override it once (preferably early in our script), the modified value (i.e., including the POST payload) will then be referenceable throughout our code. This is important since $_POST is commonly used by PHP frameworks and almost all custom scripts to extract and transform request data.
So, for example, when processing a POST payload with a content type of application/json, we need to manually parse the request contents (i.e., decode the JSON data) and override the $_POST variable, as follows:
// php
$_POST = json_decode(file_get_contents('php://input'), true);
Then when we dump the $_POST array, we see that it correctly includes the POST payload; e.g.:
array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }

Common Mistake #8: Thinking that PHP supports a character data type

Look at this sample piece of code and try guessing what it will print:
for ($c = 'a'; $c <= 'z'; $c++) {
    echo $c . "\n";
}
If you answered ‘a’ through ‘z’, you may be surprised to know that you were wrong.
Yes, it will print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’. Let’s see why.
In PHP there’s no char datatype; only string is available. With that in mind, incrementing the string z in PHP yields aa:
php> $c = 'z'; echo ++$c . "\n";
aa
Yet to further confuse matters, aa is lexicographically less than z:
php> var_export((boolean)('aa' < 'z')) . "\n";
true
That’s why the sample code presented above prints the letters a through z, but then also prints aa through yz. It stops when it reachs za, which is the first value it encounters that it “greater than” z:
php> var_export((boolean)('za' < 'z')) . "\n";
false
That being the case, here’s one way to properly loop through the values ‘a’ through ‘z’ in PHP:
for ($i = ord('a'); $i <= ord('z'); $i++) {
    echo chr($i) . "\n";
}
Or alternatively:
$letters = range('a', 'z');

for ($i = 0; $i < count($letters); $i++) {
    echo $letters[$i] . "\n";
}

Common Mistake #9: Ignoring coding standards

Although ignoring coding standards doesn’t directly lead to needing to debug PHP code, it is still probably one of the most important things to discuss here.
Ignoring coding standards can cause a whole slew of problems on a project. At best, it results in code that is inconsistent (since every developer is “doing their own thing”). But at worst, it produces PHP code that does not work or can be difficult (sometimes almost impossible) to navigate, making it extremely difficult to debug, enhance, maintain. And that means reduced productivity for your team, including lots of wasted (or at least unnecessary) effort.
Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:
  • PSR-0: Autoloading Standard
  • PSR-1: Basic Coding Standard
  • PSR-2: Coding Style Guide
  • PSR-3: Logger Interface
  • PSR-4: Autoloader
PSR was originally created based on inputs from maintainers of the most recognized platforms on the market. Zend, Drupal, Symfony, Joomla and others contributed to these standards, and are now following them. Even PEAR, which attempted to be a standard for years before that, participates in PSR now.
In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. More and more teams and projects are conforming with the PSR. Tt’s definitely recognized at this point as “the” standard by the majority of PHP developers, so using it will help ensure that new developers are familiar and comfortable with your coding standard when they join your team.

Common Mistake #10: Misusing empty()

Some PHP developers like using empty() for boolean checks for just about everything. There are case, though, where this can lead to confusion.
First, let’s come back to arrays and ArrayObject instances (which mimic arrays). Given their similarity, it’s easy to assume that arrays and ArrayObject instances will behave identically. This proves, however, to be a dangerous assumption. For example, in PHP 5.0:
// PHP 5.0 or later:
$array = [];
var_dump(empty($array));        // outputs bool(true) 
$array = new ArrayObject();
var_dump(empty($array));        // outputs bool(false)
// why don't these both produce the same output?
And to make matters even worse, the results would have been different prior to PHP 5.0:
// Prior to PHP 5.0:
$array = [];
var_dump(empty($array));        // outputs bool(false) 
$array = new ArrayObject();
var_dump(empty($array));        // outputs bool(false)
This approach is unfortunately quite popular. For example, this is the way Zend\Db\TableGateway of Zend Framework 2 returns data when calling current() on TableGateway::select() result as the doc suggests. Developer can easily become victim of this mistake with such data.
To avoid these issues, the better approach to checking for empty array structures is to use count():
// Note that this work in ALL versions of PHP (both pre and post 5.0):
$array = [];
var_dump(count($array));        // outputs int(0)
$array = new ArrayObject();
var_dump(count($array));        // outputs int(0)
And incidentally, since PHP casts 0 to falsecount() can also be used within if () conditions to check for empty arrays. It’s also worth noting that, in PHP, count()is constant complexity (O(1) operation) on arrays, which makes it even clearer that it’s the right choice.
Another example when empty() can be dangerous is when combining it with the magic class function __get(). Let’s define two classes and have a test property in both.
First let’s define a Regular class that includes test as a normal property:
class Regular
{
 public $test = 'value';
}
Then let’s define a Magic class that uses the magic __get() operator to access its test property:
class Magic
{
 private $values = ['test' => 'value'];

 public function __get($key)
 {
  if (isset($this->values[$key])) {
   return $this->values[$key];
  }
 }
}
OK, now let’s see what happens when we attempt to access the test property of each of these classes:
$regular = new Regular();
var_dump($regular->test);    // outputs string(4) "value"
$magic = new Magic();
var_dump($magic->test);      // outputs string(4) "value"
Fine so far.
But now let’s see what happens when we call empty() on each of these:
var_dump(empty($regular->test));    // outputs bool(false)
var_dump(empty($magic->test));      // outputs bool(true)
Ugh. So if we rely on empty(), we can be misled into believing that the test property of $magic is empty, whereas in reality it is set to 'value'.
Unfortunately, if a class uses the magic __get() function to retrieve a property’s value, there’s no foolproof way to check if that property value is empty or not. Outside of the class’ scope, you can really only check if a null value will be returned, and that doesn’t necessarily mean that the corresponding key is not set, since it actually couldhave been set to null.
In contrast, if we attempt to reference a non-existent property of a Regular class instance, we will get a notice similar to the following:
Notice: Undefined property: Regular::$nonExistantTest in /path/to/test.php on line 10

Call Stack:
    0.0012     234704   1. {main}() /path/to/test.php:0
So the main point here is that the empty() method should be used with care as it can lend itself to confusing – or even potentially misleading – results, if one is not careful.

Wrap-up

PHP’s ease of use can lull developers into a false sense of comfort, leaving themselves vulnerable to lengthy PHP debugging due to some of the nuances and idiosyncrasies of the language. This can result in PHP not working and problems such as those described herein.
The PHP language has evolved significantly over the course of its 20 year history. Familiarizing oneself with its subtleties is a worthwhile endeavor, as it will help ensure that the software you produce is more scalable, robust, and maintainable.