Friday, November 23, 2012

Some useful functions for manipulating array

Function
Explanation
Example
sizeof($arr) This function returns the number of elements in an array.Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array. Code: $data = array("red", "green", "blue");echo "Array has " . sizeof($data) . " elements"; ?>Output: Array has 3 elements
array_values($arr) This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.Use this function to retrieve all the values from an associative array. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); print_r(array_values($data)); ?>Output: Array ( [0] => Holmes [1] => Moriarty )
array_keys($arr) This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.Use this function to retrieve all the keys from an associative array. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); print_r(array_keys($data)); ?>Output: Array ( [0] => hero [1] => villain )
array_pop($arr) This function removes an element from the end of an array. Code: $data = array("Donald", "Jim", "Tom"); array_pop($data); print_r($data); ?>Output: Array ( [0] => Donald [1] => Jim )
array_push($arr, $val) This function adds an element to the end of an array. Code: $data = array("Donald", "Jim", "Tom"); array_push($data, "Harry"); print_r($data); ?>Output: Array ( [0] => Donald [1] => Jim [2] => Tom [3] => Harry )
array_shift($arr) This function removes an element from the beginning of an array. Code: $data = array("Donald", "Jim", "Tom"); array_shift($data); print_r($data); ?>Output: Array ( [0] => Jim [1] => Tom )
array_unshift($arr, $val) This function adds an element to the beginning of an array. Code: $data = array("Donald", "Jim", "Tom"); array_unshift($data, "Sarah"); print_r($data); ?>Output: Array ( [0] => Sarah [1] => Donald [2] => Jim [3] => Tom )
each($arr) This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); while (list($key, $value) = each($data)) { echo "$key: $value \n"; } ?>Output: hero: Holmes villain: Moriarty
sort($arr) This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort(). Code: $data = array("g", "t", "a", "s"); sort($data); print_r($data); ?>Output: Array ( [0] => a [1] => g [2] => s [3] => t )
array_flip($arr) The function exchanges the keys and values of a PHP associative array.Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns. Code: $data = array("a" => "apple", "b" => "ball"); print_r(array_flip($data)); ?>Output: Array ( [apple] => a [ball] => b )
array_reverse($arr) The function reverses the order of elements in an array.Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values. Code: $data = array(10, 20, 25, 60); print_r(array_reverse($data)); ?>Output: Array ( [0] => 60 [1] => 25 [2] => 20 [3] => 10 )
array_merge($arr) This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries. Code: $data1 = array("cat", "goat"); $data2 = array("dog", "cow"); print_r(array_merge($data1, $data2)); ?>Output: Array ( [0] => cat [1] => goat [2] => dog [3] => cow )
array_rand($arr) This function selects one or more random elements from an array.Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list. Code: $data = array("white", "black", "red"); echo "Today's color is " . $data[array_rand($data)]; ?>Output: Today's color is red
array_search($search, $arr) This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.Use this function to scan a set of index-value pairs for matches, and return the matching index. Code: $data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00"); echo "Found " . array_search("#0000cc", $data); ?>Output: Found blue
array_slice($arr, $offset, $length) This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data. Code: $data = array("vanilla", "strawberry", "mango", "peaches"); print_r(array_slice($data, 1, 2)); ?>Output: Array ( [0] => strawberry [1] => mango )
array_unique($data) This function strips an array of duplicate values.Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key. Code: $data = array(1,1,4,6,7,4); print_r(array_unique($data)); ?>Output: Array ( [0] => 1 [3] => 6 [4] => 7 [5] => 4 )
array_walk($arr, $func) This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%. Code: function reduceBy10(&$val, $key) { $val -= $val * 0.1; }$data = array(10,20,30,40); array_walk($data, 'reduceBy10'); print_r($data); ?>Output: Array ( [0] => 9 [1] => 18 [2] => 27 [3] => 36 )

Differences between echo, print and print_r in PHP

echo :
Outputs one or more strings. And echo is not a function, but a language construct. echo has a void return type.echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.
For example:
<?php   echo “Hello World”; ?>

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.
For example:
My name is <?=$name; ?>.

Note: However, short tags are discouraged to use in modern versions on PHP..

print:
print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. print has a return value of 1 so it can be used in expressions.
For example:
<?php
print(“hello world!”);
print “hello world”;
?>

However, echo is slightly faster than print.

print_r():
It displays information about a variable in a way that’s readable by humans.
For example:
<pre>
<?php
$a = array (‘a’ => ‘apple’, ‘b’ => ‘banana’, ‘c’ => array (‘x’, ‘y’, ‘z’));
print_r ($a);
?>
</pre>

PHP File Upload

Create an Upload-File Form

To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files:

<html>
<body>
<form action=”upload_file.php” method=”post”
enctype=”multipart/form-data”>
<label for=”file”>Filename:</label>
<input type=”file” name=”file” id=”file” />
<br />
<input type=”submit” name=”submit” value=”Submit” />
</form>

</body>
</html>

Notice the following about the HTML form above:

The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be uploaded
The type=”file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

Create The Upload Script

The “upload_file.php” file contains the code for uploading a file:

<?php
if ($_FILES["file"]["error"] > 0)
{
echo “Error: ” . $_FILES["file"]["error"] . “<br />”;
}
else
{
echo “Upload: ” . $_FILES["file"]["name"] . “<br />”;
echo “Type: ” . $_FILES["file"]["type"] . “<br />”;
echo “Size: ” . ($_FILES["file"]["size"] / 1024) . ” Kb<br />”;
echo “Stored in: ” . $_FILES["file"]["tmp_name"];
}
?>
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

$_FILES["file"]["name"] – the name of the uploaded file
$_FILES["file"]["type"] – the type of the uploaded file
$_FILES["file"]["size"] – the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] – the error code resulting from the file upload

PHP File

Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html>

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Closing a File
The fclose() function is used to close an open file:
<?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>

 Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length.
 Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file";  

Reading a File Line by Line The fgets() function is used to read a single line from a file.
 Note: After a call to this function the file pointer has moved to the next line.
Example
 The example below reads a file line by line, until the end of file is reached:
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
 //Output a line of the file until the end is reached
 while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
  
Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character.
 Example
 The example below reads a file character by character, until the end of file is reached:
 <?php $file=fopen("welcome.txt","r")
 or exit("Unable to open file!");
while (!feof($file))
 { echo fgetc($file); }
 fclose($file); ?>

PHP Include

Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.
The two functions are identical in every way, except how they handle errors:
  •     include() generates a warning, but the script will continue execution
  •     require() generates a fatal error, and the script will stop
These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.
Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).
PHP include() Function
The include() function takes all the content in a specified file and includes it in the current file.
If an error occurs, the include() function generates a warning, but the script will continue execution.
Example 1
Assume that you have a standard header file, called “header.php”. To include the header file in a page, use the include() function:
<html>
<body>
<?php include(“header.php”); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file, called “menu.php”, that should be used on all pages:
<a href=”index.php”>Home</a>
<a href=”about.php”>About Us</a>
<a href=”contact.php”>Contact Us</a>
If you look at the source code of the page above (in a browser), it will look like this:
<html>
<body>
<div>
<a href=”index.php”>Home</a>
<a href=”about.php”>About Us</a>
<a href=”contact.php”>Contact Us</a>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
PHP include_once() Function
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.
PHP require() Function
The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
Error Example include() Function
<html>
<body>
<?php
include(“wrongFile.php”);
echo “Hello World!”;
?>
</body>
</html>
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening ‘wrongFile.php’ for inclusion
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is executed! This is because a Warning does not stop the script execution.
Error Example require() Function
Now, let’s run the same example with the require() function.
<html>
<body>
<?php
require(“wrongFile.php”);
echo “Hello World!”;
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required ‘wrongFile.php’
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5
The echo statement is not executed, because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should not continue after an error.
PHP require_once() Function
The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.