Thursday, June 28, 2012

Introduction to Preg in PHP

The PHP function, preg_grep, is used to search an array for specific patterns and then return a new array based on that filtering. There are two ways to return the results. You can return them as is, or you can invert them (instead of only returning what matches, it would only return what does not match.) It is phrased as: preg_grep ( search_pattern, $your_array, optional_inverse ) The search_pattern needs to be a regular expression. If you are unfamiliar with them This Article gives you an overview of the syntax.
 <? 
 $data = array(0, 1, 2, 'three', 4, 5, 'six', 7, 8, 'nine', 10); 
 $mod1 = preg_grep("/4|5|6/", $data); 
 $mod2 = preg_grep("/[0-9]/", $data, PREG_GREP_INVERT); 
 print_r($mod1); 
 echo "<br>"; 
 print_r($mod2); 
 ?> 
This code would result in the following data:
Array ( [4] => 4 [5] => 5 ) 
Array ( [3] => three [6] => six [9] => nine )



First we assign our $data variable. This is a list of numbers, some in alpha form, others in numeric. The first thing we run is called $mod1. Here we are searching for anything that contains 4, 5, or 6. When our result is printed below we only get 4 and 5, because 6 was written as 'six' so it did not match our search.
Next we run $mod2, which is searching for anything that contains a numeric character. But this time we include PREG_GREP_INVERT. This will invert our data, so instead of outputting numbers, it outputs all of our entries that where not numeric (three, six and nine).
Preg_Match : 
The Preg_Match PHP function is used to search a string, and return a 1 or 0. If the search was successful a 1 will be returned, and if it was not found a 0 will be returned. Although other variables can be added, it is most simply phrased as: preg_match(search_pattern, your_string). The search_pattern needs to be a regular expression.

 <? 
 $data = "I had a box of cerial for breakfast today, and then I drank some juice.";
 if (preg_match("/juice/", $data))
 {
 echo "You had juice.<br>";
 }
 else
 {
 echo "You had did not have juice.<br>";
 }
 if (preg_match("/eggs/", $data))
 {
 echo "You had eggs.<br>";
 }
 else
 {
 echo "You had did not have eggs.<br>";
 } 
 ?>
The code above uses preg_match to check for a key word (first juice then egg) and replies based on whether it is true (1) or false (0). Because it returns these two values it is most often used in a conditional statement
Preg_Match_All :
Preg_Match_All is used to search a string for specific patterns and stores the results in an array. Unlike preg_match which stops searching after it finds a match, preg_match_all searches the entire string and records all matches. It is phrased as: preg_match_all (pattern, string, $array, optional_ordering, optional_offset)
 <? $data = "The party will start at 10:30 pm and run untill 12:30 am"; 
 preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_PATTERN_ORDER);
 echo "Full: <br>"; 
 print_r($match[0]); 
 echo "<p>Raw: <br>"; 
 print_r($match[1]); 
 echo "<p>Tags: <br>"; 
 print_r($match[2]); 
 ?> 
In our first example we use PREG_PATTERN_ORDER. We are searching for 2 things; one is the time, the other is it's am/pm tag. Our results are outputted to $match, as an array where $match[0] contains all matches, $match[1] contains all data matching our first sub-serach (the time) and $match[2] contains all data matching our second sub-search (am/pm).
 <? $data = "The party will start at 10:30 pm and run untill 12:30 am"; 
 preg_match_all('/(\d+:\d+)\s*(am|pm)/', $data, $match, PREG_SET_ORDER); 
 echo "First: <br>"; 
 echo $match[0][0] . " , " . $match[0][1] . " , ". $match [0][2] ."<br>"; 
 echo "Second: <br>"; 
 echo $match[1][0] . " , " . $match[1][1] . " , ". $match [1][2] ."<br>";
 ?> 
In our second example we use PREG_SET_ORDER. This puts each full result into an array. The first result is $match[0], with $match[0][0] being the full match, $match[0][1] being the first sub-match and $match[0][2] being the second sub-match.

Preg_replace :
The preg_replace function is used to do a find-and-replace on a string or an array. We can give it one thing to find and replace (for example it seeks out the word 'him' and changes it to 'her') or we can give it a full list of things (an array) to search for, each with a corresponding replacement. It is phrased as preg_replace ( search_for, replace_with, your_data , optional_limit, optional_count ) The limit will default to -1 which is no limit. Remember your_data can be a string or an array.
<? 
 $data = "The cat likes to sit on the fence. He also likes to climb the tree."; 
 
 $find ="/the/"; 
 $replace ="a"; 
 
 //1. replace single word 
 Echo "$data <br>"; 
 Echo preg_replace ($find, $replace, $data); 
 
 //create arrays 
 $find2 = array ('/the/', '/cat/'); 
 $replace2 = array ('a', 'dog'); 
 
 //2. replace with array values 
 Echo preg_replace ($find2, $replace2, $data); 
 
 //3. Replace just once
 Echo preg_replace ($find2, $replace2, $data, 1); 
 
 //4. Keep a count of replacements 
 $count = 0; 
 Echo preg_replace ($find2, $replace2, $data, -1, $count); 
 Echo "<br>You have made $count replacements"; 
 
 ?> 
In our first example we simply replace 'the' with 'a'. As you can see these are cAse seNsiTIvE. Then we set up an array, so in our second example we are replacing both the words 'the' and 'cat'. In our third example, we set the limit to 1, so each word is only replaced one time. Finally in our 4th example, we keep count of how many replacements we have made.
Preg_Spilit :
The function Preg_Spilit is used to take a string, and put it into an array. The string is broken up into different values in the array based upon your input. It is phrased as preg_split ( split_pattern, your_data, optional_limit, optional_flags )
 <?php 
 $str = 'I like goats. You like cats. He likes dogs.'; 
 $chars = preg_split('//', $str); 
 print_r($chars); 
 echo "<p>"; 
 $words= preg_split('/ /', $str); 
 print_r($words); 
 echo "<p>"; 
 $sentances= preg_split('/\./', $str, -1 , PREG_SPLIT_NO_EMPTY); 
 print_r($sentances); 
 ?> 
In the code above we preform three splits. In our first, we split the data by each character. In the second, we split it with a blank space, thus giving each word (and not each letter) an array entry. And in our third example we use a '.' period to split the data, therefor giving each sentence it's own array entry.
Because in our last example we use a '.' period to split, a new entry is started after our final period, so we add the flag PREG_SPLIT_NO_EMPTY so that no empty results are returned. Other available flags are PREG_SPLIT_DELIM_CAPTURE which also captures the character you are splitting by (our "." for example) and PREG_SPLIT_OFFSET_CAPTURE which captures the offset in characters where the split has occurred.




Send Mail using SMTP with PHPMailer and GMail


Website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day


Requirements

You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.


PHPMailer tutorial for GMail and Google Apps

GMail account or setup your domain for Google applications.
Download a recent version of PHPMailer (I’m using the version 5.02)
Check with your web hosting provider that port 465 (TCP out) is open, if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):

function smtpmailer($to, $from, $from_name, $subject, $body) { 
global $error;
$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465; 
$mail->Username = GUSER;  
$mail->Password = GPWD;           
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo; 
return false;
} else {
$error = 'Message sent!';
return true;
}
}


Call the function within your code:
smtpmailer('to@mail.com', '', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:

if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
// do something
}
if (!empty($error)) echo $error;




Tuesday, June 26, 2012

Optimizing PHP Code


Optimized and more efficient PHP code

  1. echo is faster than print.
  2. require_once() is expensive
  3. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  4. Unset your variables to free memory, especially large arrays.
  5. Use echo's multiple parameters instead of string concatenation.
  6. Set the maxvalue for your for-loops before and not in the loop.
  7. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  8. Avoid magic like __get, __set, __autoload
  9. Use full paths in includes and requires, less time spent on resolving the OS paths.
  10. If you need to find out the time when the script started executing, INSERT:CONTENT:END SERVER['REQUEST_TIME'] is preferred to time()
  11. See if you can use strncasecmp, strpbrk and stripos instead of regex
  12. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  13. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  14. It's better to use select statements than multi if, else if, statements.
  15. Error suppression with @ is very slow.
  16. Turn on apache's mod_deflate
  17. Close your database connections when you're done with them
  18. $row['id'] is 7 times faster than $row[id]
  19. Error messages are expensive
  20. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  21. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  22. Incrementing a global variable is 2 times slow than a local var.
  23. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  24. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  25. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  26. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  27. Methods in derived classes run faster than ones defined in the base class.
  28. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++operations. A similar method call is of course about 15 $localvar++ operations.
  29. Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
  30. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  31. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  32. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  33. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  34. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

    Example:if (strlen($foo) < 5) { echo "Foo is too short"; }



    vs.

    if (!isset($foo{5})) { echo "Foo is too short"; }

    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
  35. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  36. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  37. Do not implement every data structure as a class, arrays are useful, too
  38. Don't split methods too much, think, which code you will really re-use
  39. You can always split the code of a method later, when needed
  40. Make use of the countless predefined functions
  41. If you have very time consuming functions in your code, consider writing them as C extensions
  42. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  43. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

Tuesday, June 19, 2012

PHP Array Functions


array_chunk() Definition and Usage
The array_chunk() function splits an array into chunks of new arrays. Syntax
array_chunk(array,size,preserve_key)
Parameter Description
array Required. Specifies the array to use
size Required. Specifies how many elements each new array will contain
preserve_key Optional. Possible values:
  • true - Preserves the keys from the original array.
  • false - Default. Does not preserve the keys from the original array.

Example 1

<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2));
?>

The output of the code above will be:

Array (
[0] => Array ( [a] => Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)

Example 2

<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2,true));
?>

The output of the code above will be:

Array (
[0] => Array ( [a] => Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)
Function Description PHP
array() Creates an array 3
array_change_key_case() Returns an array with all keys in lowercase or uppercase 4
array_chunk() Splits an array into chunks of arrays 4
array_combine() Creates an array by using one array for keys and another for its values 5
array_count_values() Returns an array with the number of occurrences for each value 4
array_diff() Compares array values, and returns the differences 4
array_diff_assoc() Compares array keys and values, and returns the differences 4
array_diff_key() Compares array keys, and returns the differences 5
array_diff_uassoc() Compares array keys and values, with an additional user-made function check, and returns the differences 5
array_diff_ukey() Compares array keys, with an additional user-made function check, and returns the differences 5
array_fill() Fills an array with values 4
array_filter() Filters elements of an array using a user-made function 4
array_flip() Exchanges all keys with their associated values in an array 4
array_intersect() Compares array values, and returns the matches 4
array_intersect_assoc() Compares array keys and values, and returns the matches 4
array_intersect_key() Compares array keys, and returns the matches 5
array_intersect_uassoc() Compares array keys and values, with an additional user-made function check, and returns the matches 5
array_intersect_ukey() Compares array keys, with an additional user-made function check, and returns the matches 5
array_key_exists() Checks if the specified key exists in the array 4
array_keys() Returns all the keys of an array 4
array_map() Sends each value of an array to a user-made function, which returns new values 4
array_merge() Merges one or more arrays into one array 4
array_merge_recursive() Merges one or more arrays into one array 4
array_multisort() Sorts multiple or multi-dimensional arrays 4
array_pad() Inserts a specified number of items, with a specified value, to an array 4
array_pop() Deletes the last element of an array 4
array_product() Calculates the product of the values in an array 5
array_push() Inserts one or more elements to the end of an array 4
array_rand() Returns one or more random keys from an array 4
array_reduce() Returns an array as a string, using a user-defined function 4
array_reverse() Returns an array in the reverse order 4
array_search() Searches an array for a given value and returns the key 4
array_shift() Removes the first element from an array, and returns the value of the removed element 4
array_slice() Returns selected parts of an array 4
array_splice() Removes and replaces specified elements of an array 4
array_sum() Returns the sum of the values in an array 4
array_udiff() Compares array values in a user-made function and returns an array 5
array_udiff_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_udiff_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_uintersect() Compares array values in a user-made function and returns an array 5
array_uintersect_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_uintersect_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_unique() Removes duplicate values from an array 4
array_unshift() Adds one or more elements to the beginning of an array 4
array_values() Returns all the values of an array 4
array_walk() Applies a user function to every member of an array 3
array_walk_recursive() Applies a user function recursively to every member of an array 5
arsort() Sorts an array in reverse order and maintain index association 3
asort() Sorts an array and maintain index association 3
compact() Create array containing variables and their values 4
count() Counts elements in an array, or properties in an object 3
current() Returns the current element in an array 3
each() Returns the current key and value pair from an array 3
end() Sets the internal pointer of an array to its last element 3
extract() Imports variables into the current symbol table from an array 3
in_array() Checks if a specified value exists in an array 4
key() Fetches a key from an array 3
krsort() Sorts an array by key in reverse order 3
ksort() Sorts an array by key 3
list() Assigns variables as if they were an array 3
natcasesort() Sorts an array using a case insensitive "natural order" algorithm 4
natsort() Sorts an array using a "natural order" algorithm 4
next() Advance the internal array pointer of an array 3
pos() Alias of current() 3
prev() Rewinds the internal array pointer 3
range() Creates an array containing a range of elements 3
reset() Sets the internal pointer of an array to its first element 3
rsort() Sorts an array in reverse order 3
shuffle() Shuffles an array 3
sizeof() Alias of count() 3
sort() Sorts an array 3
uasort() Sorts an array with a user-defined function and maintain index association 3
uksort() Sorts an array by keys using a user-defined function 3
usort() Sorts an array by values using a user-defined function 3

PHP Array Constants

Constant Description PHP
CASE_LOWER Used with array_change_key_case() to convert array keys to lower case  
CASE_UPPER Used with array_change_key_case() to convert array keys to upper case  
SORT_ASC Used with array_multisort() to sort in ascending order  
SORT_DESC Used with array_multisort() to sort in descending order  
SORT_REGULAR Used to compare items normally  
SORT_NUMERIC Used to compare items numerically  
SORT_STRING Used to compare items as strings  
SORT_LOCALE_STRING Used to compare items as strings, based on the current locale 4
COUNT_NORMAL    
COUNT_RECURSIVE    
EXTR_OVERWRITE    
EXTR_SKIP    
EXTR_PREFIX_SAME    
EXTR_PREFIX_ALL    
EXTR_PREFIX_INVALID    
EXTR_PREFIX_IF_EXISTS    
EXTR_IF_EXISTS    
EXTR_REFS    

PHP HTML basic tips, tricks


PHP HTML basic tips and tricks

PHP is an HTML-embedded scripting language. The goal of the language is to allow web developers to write dynamically generated pages quickly. In the course of web development of using PHP PHP and HTML interact a lot. PHP can generate HTML, and HTML can pass information to PHP.

Encoding/decoding when passing a data through a form or URL
Certain characters, for example ‘&’, have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages.

Passing a value through HTML FORM you must include it in double quotes, and htmlspecialchars() the whole value. For exampe see the code below

<?php echo “<input name=’data’ type=’hidden’ value=’” . htmlspecialchars($data) . “‘>”; ?>

While passing a value through URL you must encode it with urlencode(). It will convert all non-alphanumeric characters except -_. with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. See example below.
<?php echo “<a href=’” . htmlspecialchars(“/nextpage.php?stage=23&data=” .urlencode($data) . “‘>\n”; ?>

Creating a PHP arrays in a HTML form

To get your FORM result sent as an array to your PHP script you name the INPUT, SELECT, TEXTAREA elements like this:
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyArray[]“>

If you do not specify the keys, the array gets filled in the order the elements appear in the form. Above example will contain keys 0, 1, 2 and 3. Notice the square brackets after the variable name, that’s what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name=”MyArray[]“>
<input name=”MyArray[]“>
<input name=”MyOtherArray[]“>
<input name=”MyOtherArray[]“>
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It’s also possible to assign specific keys to your arrays:
<input name=”AnotherArray[]“>
<input name=”AnotherArray[]“>
<input name=”AnotherArray[email]“>
<input name=”AnotherArray[phone]“>

The AnotherArray array will now contain the keys 0, 1, email and phone.

Getting results from a select multiple HTML tag.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name=”var” multiple=”yes”>
Each selected option will arrive at the action handler as var=option1, var=option2, var=option3. Each option will overwrite the contents of the previous $var variable. The solution is to use PHP’s “array from form element” feature. The following should be used:
<select name=”var[]” multiple=”yes”>
Now first item becomes $var[0], the next $var[1], etc.

Passing a variable from Javascript to PHP
Since Javascript is a client-side technology, and PHP is a server-side technology, the two languages cannot directly share variables. It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this — it allows PHP code to capture screen height and width, something that is normally only possible on the client side.
<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo “Screen width is: “. $_GET['width'] .”<br />\n”;
  echo “Screen height is: “. $_GET['height'] .”<br />\n”;
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   — post variables will need to handled differently)

  echo “<script language=’javascript’>\n”;
  echo “  location.href=\”${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}”
            . “&width=\” + screen.width + \”&height=\” + screen.height;\n”;
  echo “</script>\n”;
  exit();
}
?> 

PHP Arrays Tutorials


PHP Arrays Tutorial and PHP Array Examples

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

PHP Array Syntax: Create an Array
language-construct array() is used to create an array in PHP. See example below

array( [key =>] value
  , …
  )
key: key may be an integer or string
value: A value can be of any PHP type

Examples
$arr = array(“foo” => “bar”, 12 => true);
echo $arr["foo"]; this will print bar
echo $arr[12]; this will print 1

if you provide the brackets with no key specified, then the maximum of the existing integer indices +1 is taken as key. see below

$arr = array(5 => 1, 12 => 2); This will create an array with 2 elements
$arr[] = 56;     new key will be maximum key + 1 i.e $arr[13] = 56
$arr["x"] = 42;  This adds a new element to the array with key “x”

array(5 => 43, 32, 56, “b” => 12); This array is the same as following.
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);

Handling arrays from html form inputs to php scripts
Following example will show we can use an array from html form inputs.

HTML form with array
<input type=”checkbox” name=”selected_ids[]” value=”1?>
<input type=”checkbox” name=”selected_ids[]” value=”2?>
<input type=”checkbox” name=”selected_ids[]” value=”3?>
<input type=”checkbox” name=”selected_ids[]” value=”11?>
<input type=”checkbox” name=”selected_ids[]” value=”12?>
<input type=”checkbox” name=”selected_ids[]” value=”13?>

When we submit above form, it will generate $_POST['selected_ids'][] array to the form handling php script. This array holds all selected checkbox values from above html form. foreach() construct can be used to extract values from the array. Following code example will show how we can extract those values from the returning array.

foreach ($_POST['selected_ids'] as $key => $value) {
    echo “Key: $key; Value: $value<br>”;
}
for example if 1,2 and 12 is selected from the above html form then above code will print
Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12

Thursday, June 14, 2012

PHP: How to detect / get the real client IP address of website visitors


echo $_SERVER['REMOTE_ADDR'];
function get_ip_address() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}
Server variables


GATEWAY_INTERFACE = $_SERVER['GATEWAY_INTERFACE'];
SERVER_ADDR = $_SERVER['SERVER_ADDR'];
SERVER_NAME = $_SERVER['SERVER_NAME'];
SERVER_SOFTWARE = $_SERVER['SERVER_SOFTWARE'];
SERVER_PROTOCOL = $_SERVER['SERVER_PROTOCOL'];
REQUEST_METHOD = $_SERVER['REQUEST_METHOD'];
REQUEST_TIME = $_SERVER['REQUEST_TIME'];
QUERY_STRING = $_SERVER['QUERY_STRING'];
DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
HTTP_ACCEPT = $_SERVER['HTTP_ACCEPT'];
HTTP_ACCEPT_CHARSET = $_SERVER['HTTP_ACCEPT_CHARSET'];
HTTP_ACCEPT_ENCODING = $_SERVER['HTTP_ACCEPT_ENCODING'];
HTTP_ACCEPT_LANGUAGE = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
HTTP_CONNECTION = $_SERVER['HTTP_CONNECTION'];
HTTP_HOST = $_SERVER['HTTP_HOST'];
HTTP_REFERER = $_SERVER['HTTP_REFERER'];
HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
HTTPS = $_SERVER['HTTPS'];
REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
REMOTE_HOST = $_SERVER['REMOTE_HOST'];
REMOTE_PORT = $_SERVER['REMOTE_PORT'];
SCRIPT_FILENAME = $_SERVER['SCRIPT_FILENAME'];
SERVER_ADMIN = $_SERVER['SERVER_ADMIN'];
SERVER_PORT = $_SERVER['SERVER_PORT'];
SERVER_SIGNATURE = $_SERVER['SERVER_SIGNATURE'];
PATH_TRANSLATED = $_SERVER['PATH_TRANSLATED'];
SCRIPT_NAME = $_SERVER['SCRIPT_NAME'];
REQUEST_URI = $_SERVER['REQUEST_URI'];
PHP_AUTH_DIGEST = $_SERVER['PHP_AUTH_DIGEST'];
PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER'];
PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW'];
AUTH_TYPE = $_SERVER['AUTH_TYPE'];

Monday, June 11, 2012

PHP : Session And Cookie


PHP : Session And Cookie


difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not.
This difference determines what each is best used for. A cookie can keep information in the user's browser until deleted.
If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit.
You can store almost anything in a browser cookie. The trouble is that a user can block cookies or delete them at any time.
If, for example, your website's shopping cart utilized cookies, and a person had their browser set to block them, then they could not shop at your website.

Friday, June 8, 2012

HCL interview questions for PHP

HCL interview questions for PHP



1.what is ajax?
2.different response types in ajax?
3.different states in ajax?
4.what is json?
5.how to parse json response data?
6.how do u place two div elements side by side?
7.how do u place two images one on another?
8.stored procedures?
9.diff b/w echo and print?
10."sk.aariz@gmail.com" how to get the string b/w two dots(.) using php string functions?
11.what is shift operator?
12.what is array_shift?
13 .what is array_unshift?
14.array_combine().
$array1 = (a=>abc,a=>bc,a=>ac,a=>abcd);
$array2 = (azaad,aariz);
what ia the o/p of array_combine()?
15.how to override inline css with external css?
16.how will you validate input data in javascript and in php?(cross site scripting)
17.echo print('hello'); what is the o/p?
18.CSS sprite technique?
19.document types in html?
20.Difference between HTML and DHTML?
21.How willa create the following layout using div's?
22.what is the difference between padding and margin?
23.I have two iframes in a page how can I pass variables of one frame to another using javascript?
24.Explain singleton pattern?
25.What is Encapsulation?How will you achieve that in PHP?
26 What is load balencing? How will you do it?
27.How will you pass sessions from one server to another?
28.What is opcode & opcode cache?
29.How will you fix cross browser issues for CSS and JAVASCRIPT?
30.Is there any place in your project where the application is running slow?How will you fix that?
31.What is CSS sprite technique?
32.AJAX states?
33.In which variable you will get the response states?
34.What are environment variables.
35.Difference between PHP4 and PHP5?
36.How will you improve the page performence in front-end(front-end caching)?
37.Diff between a div teg and a span tag?
38.Explain CSS box model?
39.What is cascading?
40.Separating a number from a string using javascript?
41.CSS hacks?
42.What are access specifiers in PHP?
43.Diffenrece between Abstract class and Interface?
44.What are the different mysql Engines?
45.What is a persistance cookie?
46.What is static keyword?
47.Different query optimization techniques?
48.Inheritance in Javascript?
49.Difference between visibility :hidden and display:none?
50.XHTML Rules?
51.How will you optimize php applications?
52.What are the properties of CSS "position" ?
53.Different types of joins in mysql?
54.How will you find whether your browser supports cookies using javascript?
55.


How will you get student name and total marks of a first rank student?

56.


one employee can take interview to any number of candidates.How will you get count of candidates an employee taken interview?

Thursday, June 7, 2012

What is Moodle?


What is Moodle?


Moodle is a Learning Management System, Course Management System, or Virtual Learning Environment, depending on which term you prefer. Its goal is to give teachers and students the tools they need to teach and learn. Moodle comes from a background of Social Constructionist pedagogy, however, it can be used to support any style of teaching and learning. There are other types of software systems that are important for educational institutions, for example ePortfolios, Student Information Systems and Content repositories. Generally, Moodle does not try to re-invent these areas of functionality. Instead, tries to be the best LMS possible, and then interoperate gracefully with other systems that provide the other areas of functionality. It is, however, perfectly possible to use Moodle as a stand-alone system, without integrating it with anything else. Moodle is a web application written in PHP. Moodle is open source. Copyright is owned by individual contributors, not assigned to a single entity, although the company Moodle Pty Ltd in Perth Australia, owned by Moodle's founder Martin Dougiamas, manages the project.

What Is Moodle?
Moodle is a free, online, open source course management system
used in an increasing number of universities to conduct online and
blended courses as well as to enhance traditional classroom
courses..

Getting Started
Moodle allows instructors to add all content and activities on the course homepage. Students are able to see
and access all related content and activities from the main course page rather than having to navigate between
various areas of the course to access different types of materials. Instructors group content and activities into
modules which can be organized by topics or by weeks.
Different areas in a Moodle course include: the Activities block , the People block ,
the Administration block , Settings , Editing , Add a Resource area , and Add an Activity .
Moodle: Introduction

The Activities Block
The Activities block allows users to view a list of all course activities arranged by
category. This block will only display categories that have items available to participants.
The People Block
The People block displays the names, assigned roles, and profiles of every currently
enrolled participant in the course. You can access a user’s profile by clicking on their
name. You can edit your own profile by clicking on your name and choosing the Edit
Profile option.
The Administration Block
The Administration block is the most important block in your course. The Turn Editing
On option enables you to add activities and resources to the course. After turning editing
on there will be several small icons in each block and topic. These include arrows for
altering the position (left, right, up, or down), the update icon, the delete icon, and the eye
icon.
Changing Your Settings
To adjust the course settings, click the Settings item located under Administration block.
Here you can set the course availability to students. Additionally you may add a short
summary of the course, as well as change the number of topics.
Icons
*Note: You must create groups and set the activity to group mode to have an impact on this. Once something is in group mode, the
icon will look like .
Using the eye icons: When eye icon is ‘open’ the item is visible and accessible to participants. When the icon
is clicked the eye will ‘close’ and the item becomes hidden and inaccessible to participants. This function is
useful when you want to keep an item in your course (rather than deleting it), but do not want participants to
have access to it.
Icon Effect Icon Effect Icon Effect Icon Effect
Edit item
Close/Hide
item Delete/Remove Groups Icon*
See all
weeks/topics
Open/Show
Item Indent/shift right Move here
See one
week/topic
Help Move Icon*
Make Current (highlight)
week/topic

Making a Course Visible to Students
1. Click on Settings under the Administration block.
2. Under the Availability block, set the Availability
drop-down to This course is available to
students.
3. Click on
Note: Your course will remain in gray on the Moodle
homepage until your next login.
Changing the Number of Modules (aka Topics)
Each Moodle course, by default, is created with 10 modules (topics).
To change the number of modules, follow these steps:
1. Click on Settings under the Administration panel.
2. Under the Notes box, you will see a drop-down menu for
Number of weeks/topics. Click on the menu and select
the number of modules you want.
3. Click on .
Changing the Course Theme
Each Moodle course is created with the default Adelphi Moodle
theme. To change the theme, follow these steps:
1. Click on Settings under the Administration panel.
2. Under the Notes box, you will see a drop-down menu for
Force Theme. Click on the menu and select the desired theme.
3. Click on .
Changing the Course Description on the Moodle Homepage
1. Click on Settings under the Administration panel.
2. In the Notes box describe the course in no more than
three sentences.
3. Click on .

Navigating the Course
In order to return to the course homepage from any
other place in the course (e.g. a discussion forum,
or a resource), click on the course name (or ID) in
the upper left corner underneath the Adelphi logo,
or click on the course number on the bottom of the page.
Organizing Modules
The default view shows all course materials organized by modules as the instructor has organized them.
Modules can be displayed in different ways:
Change visibility to students by clicking the eye icon.
Collapsed modules by using the collapse button of the
module that should be the last one visible.
Expand modules by using the expand button of the module
that should be the last one visible.
Highlight the current module by using the highlight icon.
Display by Type of Content
The activities block provides a list of the types of activities deployed in the course. Clicking on a category, such
as forums, resources, or assignments, will bring up a list with all items in that category.
Display by User Activity
1. In the People block, click on Participants.
2. The following page will have the information on the
student like Address and Last Access.
3. To have a more in-depth view of student’s activity, click
on the student’s name.
4. From the students profile click on
the Activity Reports tab.
5. Orgnanized by each topic is the student’s
activity in your class. You can see the
number of times a student accessed an
activity, and the last time of access.
Allowing Pop-Up Windows to Appear in Mozilla Firefox
When Firefox prompts you that it has blocked a
popup, click Options (or Preferences) and
select Allow popups for moodle.adelphi.edu.

Assigning Roles
The Assign Roles option allows you to enroll users in your course and provide them with a specific role.
Teachers can typically assign the roles of Teacher, Non-editing teacher, and Student.
Note: Your students will be put on your Participants list as they register in the C.L.A.S.S. system. The
list will be updated regularly throughout the day. However, if a student is not showing up in your Moodle
Course, use the Assign Roles option to add them in (or add in another Teacher or Non-Editing teacher, if
you wish).
Teacher Non-editing teacher Student
Teachers can do anything
within a course, including
changing the activities and
grading students.
This role is similar to that of
Teaching Assistant. A nonediting
teacher can enter
grades for the students, but
he/she cannot edit the contents
of the course.
Students have access to the
course information provided by
the instructor and are able to
post responses in the forums,
contribute to wikis, etc.
Adding a User to Your Course
To add a user to your course and assign them one of the above roles,
follow these steps:
1. In the Administration block, click on Assign Roles.
2. Click on the role you wish to assign to the specific
user/users (Teacher, Non-editing teacher,
or Student).
3. Type in the name of the user you wish to add and
click on Search.
4. In the Search results box, select the name of the
user and click on the left-sided triangle. The user will
appear in the existing users box to the left.
5. The student’s name and email will now appear in the
existing users box.
Removing a User from Your Course
1. To remove a user from the course, select their name
from the existing users box and click on the rightsided
triangle.
Note: This step cannot be undone and a student’s data
will be erased from the course.

Quickmail
Sending an Email to Your Students
1. In the Quickmail block, click on Compose.
2. Check the box next to the name of the
student you wish to email.
3. Type in a Subject for your email
4. Type in the text of your email in the Message
box.
5. Optional: If you wish to send an attachment,
click on
6. Click on
7. Click on Continue. The email will then appear
in the inbox of the student’s designated email.

Zend Framework Coding Standard for PHP


Zend Framework Coding Standard for PHP

Overview

Scope

This document provides guidelines for code formatting and documentation to individuals and teams contributing to Zend Framework. Many developers using Zend Framework have also found these coding standards useful because their code's style remains consistent with all Zend Framework code. It is also worth noting that it requires significant effort to fully specify coding standards.

Note: Sometimes developers consider the establishment of a standard more important than what that standard actually suggests at the most detailed level of design. The guidelines in Zend Framework's coding standards capture practices that have worked well on the Zend Framework project.

Topics covered in Zend Framework's coding standards include:

  • PHP File Formatting

  • Naming Conventions

  • Coding Style

  • Inline Documentation

Goals

Coding standards are important in any development project, but they are particularly important when many developers are working on the same project. Coding standards help ensure that the code is high quality, has fewer bugs, and can be easily maintained.

PHP File Formatting

General

For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.

Note: Important: Inclusion of arbitrary binary data as permitted by __HALT_COMPILER() is prohibited from PHP files in the Zend Framework project or files derived from them. Use of this feature is only permitted for some installation scripts.

Indentation

Indentation should consist of 4 spaces. Tabs are not allowed.

Maximum Line Length

The target line length is 80 characters. That is to say, Zend Framework developers should strive keep each line of their code under 80 characters where possible and practical. However, longer lines are acceptable in some circumstances. The maximum length of any line of PHP code is 120 characters.

Line Termination

Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character. Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A.

Note: Do not use carriage returns (CR) as is the convention in Apple OS's (0x0D) or the carriage return - linefeed combination (CRLF) as is standard for the Windows OS (0x0D, 0x0A).

PHP File Formatting

General

For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.

Note: Important: Inclusion of arbitrary binary data as permitted by __HALT_COMPILER() is prohibited from PHP files in the Zend Framework project or files derived from them. Use of this feature is only permitted for some installation scripts.

Indentation

Indentation should consist of 4 spaces. Tabs are not allowed.

Maximum Line Length

The target line length is 80 characters. That is to say, Zend Framework developers should strive keep each line of their code under 80 characters where possible and practical. However, longer lines are acceptable in some circumstances. The maximum length of any line of PHP code is 120 characters.

Line Termination

Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character. Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A.

Note: Do not use carriage returns (CR) as is the convention in Apple OS's (0x0D) or the carriage return - linefeed combination (CRLF) as is standard for the Windows OS (0x0D, 0x0A).

Coding Style

PHP Code Demarcation

PHP code must always be delimited by the full-form, standard PHP tags:

  1. <?php
  2.  
  3. ?>

Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted (See General standards).

Strings

String Literals

When a string is literal (contains no variable substitutions), the apostrophe or "single quote" should always be used to demarcate the string:

  1. $a = 'Example String';

String Literals Containing Apostrophes

When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or "double quotes". This is especially useful for SQL statements:

  1. $sql = "SELECT `id`, `name` from `people` "
  2.      . "WHERE `name`='Fred' OR `name`='Susan'";

This syntax is preferred over escaping apostrophes as it is much easier to read.

Variable Substitution

Variable substitution is permitted using either of these forms:

  1. $greeting = "Hello $name, welcome back!";
  2.  
  3. $greeting = "Hello {$name}, welcome back!";

For consistency, this form is not permitted:

  1. $greeting = "Hello ${name}, welcome back!";

String Concatenation

Strings must be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:

  1. $company = 'Zend' . ' ' . 'Technologies';

When concatenating strings with the "." operator, it is encouraged to break the statement into multiple lines to improve readability. In these cases, each successive line should be padded with white space such that the "."; operator is aligned under the "=" operator:

  1. $sql = "SELECT `id`, `name` FROM `people` "
  2.      . "WHERE `name` = 'Susan' "
  3.      . "ORDER BY `name` ASC ";

Arrays

Numerically Indexed Arrays

Negative numbers are not permitted as indices.

An indexed array may start with any non-negative number, however all base indices besides 0 are discouraged.

When declaring indexed arrays with the Array function, a trailing space must be added after each comma delimiter to improve readability:

  1. $sampleArray = array(1, 2, 3, 'Zend', 'Studio');

It is permitted to declare multi-line indexed arrays using the "array" construct. In this case, each successive line must be padded with spaces such that beginning of each line is aligned:

  1. $sampleArray = array(1, 2, 3, 'Zend', 'Studio',
  2.                      $a, $b, $c,
  3.                      56.44, $d, 500);

Alternately, the initial array item may begin on the following line. If so, it should be padded at one indentation level greater than the line containing the array declaration, and all successive lines should have the same indentation; the closing paren should be on a line by itself at the same indentation level as the line containing the array declaration:

  1. $sampleArray = array(
  2.     1, 2, 3, 'Zend', 'Studio',
  3.     $a, $b, $c,
  4.     56.44, $d, 500,
  5. );

When using this latter declaration, we encourage using a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.

Associative Arrays

When declaring associative arrays with the Array construct, breaking the statement into multiple lines is encouraged. In this case, each successive line must be padded with white space such that both the keys and the values are aligned:

  1. $sampleArray = array('firstKey'  => 'firstValue',
  2.                      'secondKey' => 'secondValue');

Alternately, the initial array item may begin on the following line. If so, it should be padded at one indentation level greater than the line containing the array declaration, and all successive lines should have the same indentation; the closing paren should be on a line by itself at the same indentation level as the line containing the array declaration. For readability, the various "=>" assignment operators should be padded such that they align.

  1. $sampleArray = array(
  2.     'firstKey'  => 'firstValue',
  3.     'secondKey' => 'secondValue',
  4. );

When using this latter declaration, we encourage using a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.

Classes

Class Declaration

Classes must be named according to Zend Framework's naming conventions.

The brace should always be written on the line underneath the class name.

Every class must have a documentation block that conforms to the PHPDocumentor standard.

All code in a class must be indented with four spaces.

Only one class is permitted in each PHP file.

Placing additional code in class files is permitted but discouraged. In such files, two blank lines must separate the class from any additional PHP code in the class file.

The following is an example of an acceptable class declaration:

  1. /**
  2. * Documentation Block Here
  3. */
  4. class SampleClass
  5. {
  6.     // all contents of class
  7.     // must be indented four spaces
  8. }

Classes that extend other classes or which implement interfaces should declare their dependencies on the same line when possible.

  1. class SampleClass extends FooAbstract implements BarInterface
  2. {
  3. }

If as a result of such declarations, the line length exceeds the maximum line length, break the line before the "extends" and/or "implements" keywords, and pad those lines by one indentation level.

  1. class SampleClass
  2.     extends FooAbstract
  3.     implements BarInterface
  4. {
  5. }

If the class implements multiple interfaces and the declaration exceeds the maximum line length, break after each comma separating the interfaces, and indent the interface names such that they align.

  1. class SampleClass
  2.     implements BarInterface,
  3.                BazInterface
  4. {
  5. }

Class Member Variables

Member variables must be named according to Zend Framework's variable naming conventions.

Any variables declared in a class must be listed at the top of the class, above the declaration of any methods.

The var construct is not permitted. Member variables always declare their visibility by using one of the private, protected, or public modifiers. Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set & get).

Functions and Methods

Function and Method Declaration

Functions must be named according to Zend Framework's function naming conventions.

Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers.

As with classes, the brace should always be written on the line underneath the function name. Space between the function name and the opening parenthesis for the arguments is not permitted.

Functions in the global scope are strongly discouraged.

The following is an example of an acceptable function declaration in a class:

  1. /**
  2. * Documentation Block Here
  3. */
  4. class Foo
  5. {
  6.     /**
  7.      * Documentation Block Here
  8.      */
  9.     public function bar()
  10.     {
  11.         // all contents of function
  12.         // must be indented four spaces
  13.     }
  14. }

In cases where the argument list exceeds the maximum line length, you may introduce line breaks. Additional arguments to the function or method must be indented one additional level beyond the function or method declaration. A line break should then occur before the closing argument paren, which should then be placed on the same line as the opening brace of the function or method with one space separating the two, and at the same indentation level as the function or method declaration. The following is an example of one such situation:

  1. /**
  2. * Documentation Block Here
  3. */
  4. class Foo
  5. {
  6.     /**
  7.      * Documentation Block Here
  8.      */
  9.     public function bar($arg1, $arg2, $arg3,
  10.         $arg4, $arg5, $arg6
  11.     ) {
  12.         // all contents of function
  13.         // must be indented four spaces
  14.     }
  15. }

Note: Pass-by-reference is the only parameter passing mechanism permitted in a method declaration.

  1. /**
  2. * Documentation Block Here
  3. */
  4. class Foo
  5. {
  6.     /**
  7.      * Documentation Block Here
  8.      */
  9.     public function bar(&$baz)
  10.     {}
  11. }

Call-time pass-by-reference is strictly prohibited.

The return value must not be enclosed in parentheses. This can hinder readability, in additional to breaking code if a method is later changed to return by reference.

  1. /**
  2. * Documentation Block Here
  3. */
  4. class Foo
  5. {
  6.     /**
  7.      * WRONG
  8.      */
  9.     public function bar()
  10.     {
  11.         return($this->bar);
  12.     }
  13.  
  14.     /**
  15.      * RIGHT
  16.      */
  17.     public function bar()
  18.     {
  19.         return $this->bar;
  20.     }
  21. }

Function and Method Usage

Function arguments should be separated by a single trailing space after the comma delimiter. The following is an example of an acceptable invocation of a function that takes three arguments:

  1. threeArguments(1, 2, 3);

Call-time pass-by-reference is strictly prohibited. See the function declarations section for the proper way to pass function arguments by-reference.

In passing arrays as arguments to a function, the function call may include the "array" hint and may be split into multiple lines to improve readability. In such cases, the normal guidelines for writing arrays still apply:

  1. threeArguments(array(1, 2, 3), 2, 3);
  2.  
  3. threeArguments(array(1, 2, 3, 'Zend', 'Studio',
  4.                      $a, $b, $c,
  5.                      56.44, $d, 500), 2, 3);
  6.  
  7. threeArguments(array(
  8.     1, 2, 3, 'Zend', 'Studio',
  9.     $a, $b, $c,
  10.     56.44, $d, 500
  11. ), 2, 3);

Control Statements

If/Else/Elseif

Control statements based on the if and elseif constructs must have a single space before the opening parenthesis of the conditional and a single space after the closing parenthesis.

Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses are encouraged to improve logical grouping for larger conditional expressions.

The opening brace is written on the same line as the conditional statement. The closing brace is always written on its own line. Any content within the braces must be indented using four spaces.

  1. if ($a != 2) {
  2.     $a = 2;
  3. }

If the conditional statement causes the line length to exceed the maximum line length and has several clauses, you may break the conditional into multiple lines. In such a case, break the line prior to a logic operator, and pad the line such that it aligns under the first character of the conditional clause. The closing paren in the conditional will then be placed on a line with the opening brace, with one space separating the two, at an indentation level equivalent to the opening control statement.

  1. if (($a == $b)
  2.     && ($b == $c)
  3.     || (Foo::CONST == $d)
  4. ) {
  5.     $a = $d;
  6. }

The intention of this latter declaration format is to prevent issues when adding or removing clauses from the conditional during later revisions.

For "if" statements that include "elseif" or "else", the formatting conventions are similar to the "if" construct. The following examples demonstrate proper formatting for "if" statements with "else" and/or "elseif" constructs:

  1. if ($a != 2) {
  2.     $a = 2;
  3. } else {
  4.     $a = 7;
  5. }
  6.  
  7. if ($a != 2) {
  8.     $a = 2;
  9. } elseif ($a == 3) {
  10.     $a = 4;
  11. } else {
  12.     $a = 7;
  13. }
  14.  
  15. if (($a == $b)
  16.     && ($b == $c)
  17.     || (Foo::CONST == $d)
  18. ) {
  19.     $a = $d;
  20. } elseif (($a != $b)
  21.           || ($b != $c)
  22. ) {
  23.     $a = $c;
  24. } else {
  25.     $a = $b;
  26. }

PHP allows statements to be written without braces in some circumstances. This coding standard makes no differentiation- all "if", "elseif" or "else" statements must use braces.

Switch

Control statements written with the "switch" statement must have a single space before the opening parenthesis of the conditional statement and after the closing parenthesis.

All content within the "switch" statement must be indented using four spaces. Content under each "case" statement must be indented using an additional four spaces.

  1. switch ($numPeople) {
  2.     case 1:
  3.         break;
  4.  
  5.     case 2:
  6.         break;
  7.  
  8.     default:
  9.         break;
  10. }

The construct default should never be omitted from a switch statement.

Note: It is sometimes useful to write a case statement which falls through to the next case by not including a break or return within that case. To distinguish these cases from bugs, any case statement where break or return are omitted should contain a comment indicating that the break was intentionally omitted.

Inline Documentation

Documentation Format

All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: » http://phpdoc.org/

All class files must contain a "file-level" docblock at the top of each file and a "class-level" docblock immediately above each class. Examples of such docblocks can be found below.

Files

Every file that contains PHP code must have a docblock at the top of the file that contains these phpDocumentor tags at a minimum:

  1. /**
  2. * Short description for file
  3. *
  4. * Long description for file (if any)...
  5. *
  6. * LICENSE: Some license information
  7. *
  8. * @category   Zend
  9. * @package    Zend_Magic
  10. * @subpackage Wand
  11. * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  12. * @license    http://framework.zend.com/license   BSD License
  13. * @version    $Id:$
  14. * @link       http://framework.zend.com/package/PackageName
  15. * @since      File available since Release 1.5.0
  16. */

The @category annotation must have a value of "Zend".

The @package annotation must be assigned, and should be equivalent to the component name of the class contained in the file; typically, this will only have two segments, the "Zend" prefix, and the component name.

The @subpackage annotation is optional. If provided, it should be the subcomponent name, minus the class prefix. In the example above, the assumption is that the class in the file is either "Zend_Magic_Wand", or uses that classname as part of its prefix.

Classes

Every class must have a docblock that contains these phpDocumentor tags at a minimum:

  1. /**
  2. * Short description for class
  3. *
  4. * Long description for class (if any)...
  5. *
  6. * @category   Zend
  7. * @package    Zend_Magic
  8. * @subpackage Wand
  9. * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  10. * @license    http://framework.zend.com/license   BSD License
  11. * @version    Release: @package_version@
  12. * @link       http://framework.zend.com/package/PackageName
  13. * @since      Class available since Release 1.5.0
  14. * @deprecated Class deprecated in Release 2.0.0
  15. */

The @category annotation must have a value of "Zend".

The @package annotation must be assigned, and should be equivalent to the component to which the class belongs; typically, this will only have two segments, the "Zend" prefix, and the component name.

The @subpackage annotation is optional. If provided, it should be the subcomponent name, minus the class prefix. In the example above, the assumption is that the class described is either "Zend_Magic_Wand", or uses that classname as part of its prefix.

Functions

Every function, including object methods, must have a docblock that contains at a minimum:

  • A description of the function

  • All of the arguments

  • All of the possible return values

It is not necessary to use the "@access" tag because the access level is already known from the "public", "private", or "protected" modifier used to declare the function.

If a function or method may throw an exception, use @throws for all known exception classes:

  1. @throws exceptionclass [description]