0% found this document useful (0 votes)
66 views21 pages

Function With Array

The document discusses PHP functions. It defines functions as reusable pieces of code that perform tasks. There are user-defined functions created by the programmer and built-in functions included with PHP. User-defined functions use keywords like function, return, and parameters to define the function name, code, and passing of values. Built-in functions include array, date/time, file, and string functions. The document also covers function scope, including local, global, static, and superglobal variables.

Uploaded by

Online User
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
66 views21 pages

Function With Array

The document discusses PHP functions. It defines functions as reusable pieces of code that perform tasks. There are user-defined functions created by the programmer and built-in functions included with PHP. User-defined functions use keywords like function, return, and parameters to define the function name, code, and passing of values. Built-in functions include array, date/time, file, and string functions. The document also covers function scope, including local, global, static, and superglobal variables.

Uploaded by

Online User
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

PHP Function :

A function is a self­contained piece of code which carries out a particular task (or function!).
key benefit of using functions is that they are reusable; if you have a task that needs to be 
performed a number of times, a function is an ideal solution. They can be either defined by 
you or by PHP (PHP has a rich collection of built­in functions).

Types of functions
• User defined function
• Returning value function
• Internal (in­built) function

User Defined Function: 
The actual syntax for creating a function is pretty self­explanatory, but you can be the judge of 
that. First, you must tell PHP that you want to create a function. You do this by typing the 
keyword function followed by your function name .Function names follow the same rules as 
other labels in PHP. A valid function name starts with a letter or underscore, followed by any 
number of letters, numbers, or underscores .

Syntax :
function function_name(){
// Code to be executed by function
}
To call user defined function , we can just call by it's  name.
function_name();

Example :
//Defining function
function printMyName() {
echo "My Name is Basanta Chapagain";
}
// Call function 
printMyName();

Output : My Name is Basanta Chapagain


In the example above, we create a function named "printMyName()". The opening curly brace 
( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the 
end of the function.

Returning value function :
user defined function also can  return some values based on passed argument  using return 
statement. A function can return a value using the return statement in conjunction with a 
value or object. return stops the execution of the function and sends the value back to the 
calling code. You can return more than one value from a function using return array(1,2,3,4). 
Following example takes two integer parameters and calculate square and then returns their 
sum to the calling program. Note that return keyword is used to return a value from a 
function.
<?php
function square($len){
return 4*$len;
}
square(4);
?>

PHP Functions with Parameters:

PHP gives you option to pass your parameters inside a function. You can pass as many as 
parameters your like. These parameters work like variables inside your function. 

Following example takes two integer parameters and add them together and then print them.
<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
 Variable parameter counts

func_num_args

Returns the number of arguments passed to the function

Example :
function test()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs ";
}

test(61, 65, 38, 25,98);   
?>

func_get_arg

mixed func_get_arg ( int $arg_num )
Gets the specified argument from a user­defined function's argument list. Start with 0

<?php
function test()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br /> ";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "<br /> ";
     }
}

test (14, 26, 73,45,56);
?>
PHP variable and function scope : 

Scope can be defined as the range of availability a variable has to the program in which it is 
declared. The scope of a variable in PHP is the context in which the variable was created, and 
in which it can be accessed. PHP variables can be one of four scope types: 
• Local variables
• Function parameters
• Global variables
• Static variables.

Local Variables:
A variable declared in a function is considered local . Any assignment outside of that function  
will be considered to be an entirely different variable from the one contained in the function:

<?php 
$marks = 40;
function assignMarks () {
$x = 60;
print "\$Marks inside function is $marks";
}
assignMarks();
print "\$marks outside of function is $marks";
?>

output :
$marks inside function is 60.
$ marks outside of function is 40.

Function Parameters:
Function parameters are declared after the function name and inside parentheses. They are 
declared much like a typical variable would be:

<?php
// find reminder a value by divided by 3  and return it to the caller
function reminder ($value) {
    $value = $value % 3;
    return $value;
}
$retval = reminder (11);
Print "Return value is $retval\n";
?>

O/P: 
Return value is 2

Global Variables:
In contrast to local variables and function parameter , a global variable can be accessed in any 
part of the program. However, in order to be modified, a global variable must be explicitly  
declared   to   be   global  in   the  function   in   which   it   is  to   be  modified.   This  is   accomplished, 
conveniently enough, by placing the keyword GLOBAL  or global in front of the variable that 
should be recognized as global. Placing this keyword in front of an already existing variable 
tells PHP to use the variable having that name.

<?php
$first_num = 15;
function add() {
GLOBAL $first_num;
$first_num++;
print "Somevar is $first_num";
}
add();
?>

$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;

Sum();
echo $b;
?>
The above script will output 3. By declaring $a and $b global within the function, all 
references to either variable will refer to the global version. There is no limit to the number of 
global variables that can be manipulated by a function.
PHP provides a special set of predefined global arrays containing various useful nuggets of 
information. These arrays are known as superglobals because they're accessible from 
anywhere in your script , including inside functions,  and you don't need to declare them as 
global using the global keyword.
Here's a full list of the superglobals available in PHP, 

$GLOBALS Contains a list of all global variables in the script (excluding 
superglobals)
$_GET Holds a list of all form fields sent by the browser using the GET request
$_POST Holds a list of all form fields sent by the browser using the POST request
$_COOKIE Holds a list of all cookies sent by the browser
$_REQUEST Contains all the keys and values in the $_GET,$_POST and $_COOKIE 
arrays combined
$_FILES Holds a list of any files uploaded by the browser
$_SESSION Allows you to store and retrieve persistent session variables for the 
current browser
$_SERVER Holds server environment info such as the filename of the running 
script, and the IP address of the browser.
$_ENV Contains a list of environment variables passed to PHP. These can 
include variables provided by the shell, as well as CGI variables.

For example, we can use the $_GET superglobal to retrieve a value included in the query string 
of the script's URL, and display the value in the page:
<?php

$yourName = $_GET['yourName'];
echo "Hello, $yourName!";

?>
If you run the above script using a URL along the lines of   test.php?yourName=Ram the script 
displays:

O/P : Hello, Ram
The $GLOBALS superglobal is handy because it lets you access global variables within 
functions without needing to use the global keyword. 
<?php
$globalName = "Zoe";

function sayHello() {
  echo "Hello, " . $GLOBALS['globalName'] . "!<br>";
}
echo $GLOBALS['globalName'];
sayHello();  // Displays "Hello, Zoe!"
echo $GLOBALS['globalName'];

?>

Static Variables:
In contrast to the variables declared as function parameters, which are destroyed on the 
function's exit, a static variable will not lose its value when the function exits and will still hold 
that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the 
variable name.

<?php
function keep_track() {
   STATIC $count = 0;
   $count++;
   print $count;
   print "
";
}
keep_track();
keep_track();
keep_track();
?>
When you create a local variable inside a function, that variable only hangs around while the 
function is being run. As soon as the function exits, the local variable vanishes. When the 
function is called again, a new local variable is created.
While static variables remember their values across function calls, they only last as long as the 
running script. Once the script exits, a static variable gets destroyed, just like local and global 
variables do.
PHP inbuilt function:

•  PHP Calender Functions
•  PHP Array Functions
•  PHP Class/Object Functions
•  PHP Character Functions
•  PHP Date & Time Functions
•  PHP Directory Functions
•  PHP Error Handling Functions
•  PHP File System Functions
•  PHP MySQL Functions
•  PHP Network Functions
•  PHP ODBC Functions
•  PHP String Functions
•  PHP SimpleXML Functions
•  PHP XML Parsing Functions

PHP Array :
Array is one of the most vital part in every programming languages. It is also important to 
know what facilities and built­in functionality a programming language provides. PHP provides 
a very strong set of such efficient ways to deal with array data type.

Types Of PHP Arrays:
There are three basic types:

•Indexed Array: Arrays with sequential numeric index, such as 0,1,2 etc. Example:

$myarray = array();

$myarray[0] = "test data 1";

$myarray[1] = "test data 2";

$myarray[3] = "test data 3";

•Associative Array:This is the most frequently used type of PHP Arrays whose elements 
are defined in key/value pair.Example:

$myarray = array();

$myarray["key1"] = "value 1";

$myarray["key2"] = "value 2";

$myarray["key3"] = "value 3";

•Multidimensional Array: Arrays whose elements may contains one or more arrays. 
There is no limit in the level of dimensions.Example:

$myarray = array();

$myarray[0] = array("data01","data02","data03");

$myarray[1] = array("data11","data12","data13");

Following functions allow you to interact with and manipulate arrays in various ways. 
Arrays are essential for storing, managing, and operating on sets of variables. 

Merge Two Array In PHP Into Single One:

The “array_merge” function provides the easiest way to merge a list of arrays. It can take as 
much parameters as you give to it and it will merge all of them into a single one and return 
back to you. Example usage:
Syntax : array array_merge ( array $array1 [, array $array2 [, array $array3...]] );
Example :
$myarray1 = array(1,2,3);
$myarray2 = array(4,5,6);
$myarray3 = array(7,8,9);
$single_merged_array = array_merge($myarray1,$myarray2,$myarray3);
print_r($single_merged_array);

Merge array recursively : 

array array_merge_recursive ( array $array1 [, array $array2...] )

Merges the elements of one or more arrays together so that the values of one are appended to 
the end of the previous one.

If the input arrays have the  same string keys,  then the values for these keys are merged 


together into an array, and this is done recursively, so that if one of the values is an array itself, 
the function will merge it with a corresponding entry in another array too.

Example :

<?php

$array1=array("a"=>"Horse","b"=>"Cat","c"=>"Dog");
$array2=array("d"=>"Cow","a"=>"Cat","e"=>"elephant");

print_r(array_merge_recursive($array1,$array2));
?> 
OUTPUT : 

Array 


        [a] => Array ( [0] => Horse [1] => Cat ) 
        [b] => Cat 
        [c] => Dog 
        [d] => Cow 
        [e] => elephant 
)
Sorting Arrays In PHP:
there are two ways to sort elements of array. If you want a simple default ascending 
order sorting with non­object array elements, then you can go for “sort” function. You 
just pass the array as parameter and it will sort the array and returns true if succeed.

sort( $array [, $sort_flags] );
sort_flag   = >  Optional. Specifies how to sort the array values. Possible values:

•SORT_REGULAR ­ Default. Treat values as they are (don't change types)
•SORT_NUMERIC ­ Treat values numerically
•SORT_STRING ­ Treat values as strings
•SORT_LOCALE_STRING ­ Treat values as strings, based on local settings
Example :
$simple_array = array("dbc","bcd”,"abc");

if(sort($simple_array)){
print_r($simple_array);
}

krsort ( $array, $sort_flag ) :The krsort() function sorts an array by the keys in reverse order. 
The values keep their original keys. 

Example :

<?php

$transport = array( a=>'foot', b=>'bike', c=>'car', d=>'plane');
krsort($transport);
print_r($transport);
?> 
O/P : Array ( [d] => plane [c] => car [b] => bike [a] => foot )
ksort($array,sort_flag);
The ksort() function sorts an array by key, maintaining key to data correlations. This is useful 
mainly for associative arrays.

<?php
$transport = array( a=>'foot', b=>'bike', c=>'car', d=>'plane');
ksort($transport);
print_r($transport);
?> 

Difference Between Two PHP Arrays:

If you are trying to exclude few elements from an array which are common to another array’s 
elements, then “array_diff” is the perfect function for you. Use as below:

array_diff($array 1, $array2);

$myarray1 = array(1,2,3,4,­1,­2);

$myarray2 = array(­1,­2);
$filtered_array = array_diff($myarray1,$myarray2);
print_r($filtered_array);

          array array_diff_key ( array $array1, array $array2 [, array $...] )

Get Common Elements Among Two PHP Arrays:

If you are trying to get only the common elements from two different arrays, “array_intersect” 
is the proper function for such purpose. Simple PHP example for this operation is given below:

$myarray1 = array(1,2,3,4,­1,­2);
$myarray2 = array(­1,­2,3);
$common_array = array_intersect($myarray1,$myarray2);
print_r($common_array);
Getting Keys/Values Separately From Associative Array:

If you somehow need to get either only the keys or values of an associative array, you can do 
so with help of “array_keys” or “array_values” functions. See the example below:

$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");

print_r(array_keys($my_array));
echo "<br>";
print_r(array_values($my_array));

Convert An PHP Array To String And Vice­versa:

This one I need frequently :p . Often I need to convert a string to an array of elements and also 
convert an array to a single string value with delimited characters like “,” etc. These operations 
can be achieved by “implode” and “explode” php functions. Lets see their usage:

$myarray1 = array(1,2,3,4,­1,­2);
$converted_string = implode(",",$myarray1);
echo $converted_string;
$converted_values = explode(",",$converted_string);
echo print_r($converted_values);

Retrieve Only A Portion Of An Array:

Well you do have a big array, but at some point, you need only limited part of it without 
destroying other elements. In cases like that, “array_chunk” comes to the relief.

$limited_array = array_chunk($my_array,10);
print_r($limited_array);

Remove Duplicates From PHP Array:

“array_unique” – another angel function to me :D. It will remove duplicate entries and make 
the array contains only distinct elements. Just pass the array as its parameter and we are done! 
If you are trying to make unique elements which are of object type, then make sure to 
implement your own _toString() function inside the class and return a string value that 
represents the identity of the object and it should do the work fine.

$unique_array = array_unique($my_array_with_duplicates);
print_r($unique_array);

Find number of elements in an array 
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.

$data = array("red", "green", "blue");
echo "Array has " . sizeof($data) . " elements";

Output:
Array has 3 elements

Removes an element from the end of an array

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
)
Adds an element to the end of an array :

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
)
Removes an element from the beginning of an array:

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
)
Adds an element to the beginning of an array

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
)
Iteratively traverse an array with key and value:

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

Exchanges the keys and values of a PHP associative array

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
)
Reverses the order of elements in an array: 

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
)

Selects one or more random elements from an array

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
)

You might also like