Function

In PHP.., array is an implementation of an ordered Map. A bản đồ is an abstract data type of key value pairs. It is an interface, a contract.

Bạn đang xem: Function

Đang xem: Php

A map can have different implementations like a HashTable, HashMap, Dictionary, etc. In PHPhường., underlying implementation of an array actually points khổng lồ a HashTable.

So if you are looking for a HashTable data type in PHPhường., look nowhere, it is the Array itself.

To know the internals, I recommover you to lớn go through the PHP source for Array and HashTable.

You can use the array khổng lồ store a group of data and refer them via a single variable name. Each array thành quả is stored as a key and value pair.

*

How lớn find the kích thước of a PHP Array?

You can use count function khổng lồ find the size of an array. sizeof is an alias of the function count.

You might think what is the big khuyến mãi with count function. If you are a beginner, you will definitely learn something new, so read on and bởi vì not skip this. Also rethành viên to lớn check the example script.

count

The syntax of PHPhường count function is,

count(var array_variable, mode)If the value of array_variable is not phối or having an empty array, then count will return 0. And, if it is not an array, then count will return 1. In PHP version 7 onwards, you will get a warning.

So whenever you need to check if a PHPhường array is empty, you need to use the count function. Ensure that you pass array to lớn the count function.

0) emang lại “array has elements”;else emang lại “array is empty”;?>The argument mode is optional và it specifies the mode of operation lớn be used in calculating array length. Possible options are,

COUNT_NORMAL – will return the length of an array in depth 0. This is the mặc định.COUNT_RECURSIVE – for recursive sầu count operation, till it reaches depth n. This recursive Điện thoại tư vấn will be continued infinitely, till it reaches depth n or the program execution time limit is elapsed.Example: PHP.. count() with mode option

Following script is an example for count function khổng lồ calculate a number of elements available to a depth cấp độ. Let us use a two-dimensional array so that we can specify the mode depth.

$toys = array(array(“name”=>”Mechanical Cars”,”category”=>”pull back”),array(“name”=>”Jigsaw”,”category”=>”puzzles”),array(“name”=>”HiTech Cars”,”category”=>”remote”),array(“name”=>”Teddy Bears”,”category”=>”soft”),array(“name”=>”Baby pillow”,”category”=>”soft”),array(“name”=>”Chinese Checker”,”category”=>”puzzles”),array(“name”=>”Jumbo Helicopter”,”category”=>”remote”));Now, we can invoke count function by passing different possible mode options.

$array_length = count($toys,COUNT_NORMAL);//(OR) $array_length = count($toys);$array_length = count($toys,COUNT_RECURSIVE);print “”;print_r($array_length);print “”;In the above sầu PHPhường code, the count() is invoked with normal, mặc định & recursive sầu mode. Returned values are stored inlớn an array named, $array_length, by specifying the appropriate name indices.

Following is the output of this program.

Array( => 7 => 7 => 21)

sizeof

This function sizeof is an alias of PHP count function. It accepts the same phối of arguments as lượt thích as count().

We can replace the count with sizeof in the above sầu PHP.. code lớn compare the results of both functions which will be same for both functions calls.

Alias functions in PHPhường are preserved for providing backward compatibility. If you are writing a new program it is better not khổng lồ go with the alias functions as there is a chance khổng lồ deprecate it in the future.

How lớn convert an array lớn a string in PHP?

You can use the built-in function implode khổng lồ convert an array to lớn a string.

PHPhường Implode

implode function accepts an array & a separator as parameters. It combines each of the array elements và separates them with the passed separator argument. For example,

$str_concát = “|”;$meaning_array = array(“implode”,”join”,”concatenate”);$imploded_string = implode($str_conmèo,$meaning_array);echo $imploded_string; // implode|join|concatenateIf you use a comma (,) as separator, then you will be able to lớn covert the array as CSV. This will be a useful utility in many situations.

How lớn convert a string lớn an array in PHP?

You can use the built-in function explode to convert a string to lớn an array. split function is deprecated & so vày not use it for creating an array based on a string.

PHPhường Explode

explode is to lớn split the string into an array of elements based on a given separator. explode accepts separator and a string as its argument.

$input_string = “implode|join|concatenate”;$str_explode = “|”;$exploded_array = explode($str_explode,$input_string );emang lại “”;print_r($exploded_array); emang lại “”;This example code accepts the resultant string data of implode example we just saw above sầu. Explode splits string data based on the argument separator “|”. The output is,

Array( => implode => join => concatenate)Explode within LimitPHP explode() accepts a third optional argument limit to mix target length or boundary for performing explode operation. explode will take entire string as default if limit is not specified.

$exploded_array = explode($str_explode,$input_string,2);this will return,

Array( => implode => join|concatenate)

Finding intersection, difference and union of arrays

PHP has wide array of in-built functions for handling arrays. Intersection, difference và union are performed quite regularly when using arrays. PHP has got good phối of functions in-built khổng lồ handle these operations.

*
*

Array intersection

PHP array_intersect function is used lớn find intersection between arrays. This function can accept multiple arguments khổng lồ compare. After comparison, this function returns an array of intersecting elements that are present in all the argument arrays.

Syntax:

array_intersect($input_array1,$input_array2,$input_array3…)Array intersection exampleIn this example, we are going to pass four arrays as parameters.

“;print_r($arrayIntersect);print “”;?>This program prints resultant array containing values that are present in all the four input đầu vào arrays. The output is,

Array( => Baby Pillow => Teddy Bear)Other Array intersection functions in PHPPHP.. includes more variety of functions to lớn calculate intersection of elements amuốn input arrays.

array_intersect_key – returns intersecting elements with respect lớn the keys.array_interset_assoc – returns intersecting elements with respect khổng lồ keys & values.array_intersect_ukey – returns intersecting elements on the basis of custom function by providing an algorithm for the intersection.

Array difference

By using PHP array difference functions, we can find differences between arrays with respect khổng lồ their keys or values.

array_diff_keyarray_diff_assoc

Array differences can also be found, based on the index check by using the custom made functions. They are used as a callbaông chồng.

array_diff_ukeyarray_diff_uassoc

The list goes on. By comparing their entries with the use of user-defined callbachồng functions.

Xem thêm: Order Fulfillment Là Gì ? Nghĩa Của Từ Fulfill Trong Tiếng Việt

array_udiffarray_udiff_assocarray_udiff_uassocarray_diff

It accepts at least two arrays, but, maximum in any number of arrays, as its arguments, thereby, the elements from the first array will be compared with the rest of the array elements.

array_diff_key

This function is used as similar as array_diff, but for comparing array elements with respect to lớn their key.

array_diff_assoc

This function is used lớn compare the values between given arrays, by considering the key index associated with these values.

Array difference example

“apple”, “fruit2” => “grapes”,”friut3″ =>”banana”);$array_against = array(“fruit1” => “orange”, “fruit2” => “grapes”,”friut4″ => “banana”);$value_differences = array_diff($array_from, $array_against);$key_differences = array_diff_key($array_from, $array_against);$assoc_index_differences = array_diff_assoc($array_from, $array_against);print “”;print_r($value_differences);print_r($key_differences);print_r($assoc_index_differences);print “”;?>Array difference example’s output below:

Array( => apple)Array( => banana)Array( => táo Apple => banana)PHPhường Array difference with callbaông xã – closuresIt is possible khổng lồ define your own custom xúc tích lớn find difference between arrays. User-defined functions can be passed for callback.

Passing functions as argument is a cool feature in PHP.. They are called anonymous functions and implemented using closures.

array_diff_ukey , array_diff_uassoc for key and index based differences.array_udiff , array_udiff_assoc for value based array difference.array_udiff_uassoc used khổng lồ perkhung both array value và key index comparison.

Creating variables from array keys

PHP has a function named extract to create variables using array keys. It creates PHP variables with the name of each array keys. It uses an associative sầu array as input đầu vào argument.

extract

This function accepts three arguments as listed below.

$input_array – Associative array from which the keys are converted inkhổng lồ PHP. variables.$extract_type – Defines options to lớn create a new variable or overwrite existing variables.EXTR_OVERWRITE, EXTR_SKIPhường, EXTR_IF_EXISTS, EXTR_REFS are the options.$variable_prefix – String to lớn prefix with the variable name to lớn be created.PHPhường. extract example

“Stories”,”partB” => “Rhymes”, “partC” => “Concepts”);extract($input_array,EXTR_OVERWRITE);print “$partA=”. $partA . “”;print “$partB=”. $partB . “”;print “$partC=”. $partC . “”;?>Caution on using extractYou should not use extract on user input data. If you vị so, it may cause security concerns. Do not use this function, unless otherwise you know what you are doing!

Frequently used built-in Array functions

Let us see some of the widely used PHPhường array functions with PHP. code snippet examples.

range

PHPhường range() function is used get the array of elements in the range between the start & over parameters. The range can be a numeric or alphabet. The following code shows how lớn get the array of alphabets that exists between “e” và “i”.

$character_array = range(“e”,”i”); // returns array(“e”,”f”,”g”,”h”,”i”);

reset

The reset() function is used to lớn rephối the position of the array pointer. It requires the array variable as its argument, to move sầu the array pointer to its original position.

$character_array = range(“e”,”i”); // returns array(“e”,”f”,”g”,”h”,”i”);print next($character_array); // prints fprint next($character_array); // prints greset($character_array);print current($character_array); // prints the first element “e” after reset

array_slice

It is used lớn get the sub-array from the given input array. It accepts the input đầu vào array, starting position as offphối and the length of the sub array.

The length parameter is optional. If it is not specified, the length of the đầu vào array will be taken by mặc định. The fourth argument is to preserve sầu keys by avoiding the default index reordering behavior.

$color_array = array(“Red”,”Blue”,”Green”,”Yellow”,”Brown”); sliced_array = array_slice($color_array,1,3);// now the sliced array will be array(“Blue”,”Green”,”Yellow”)

array_splice

This function is similar to array_slice & it can also replace the removed elements with the new set of elements. The length of the removed set & new array should be same.

$character_array = array(“e”,”f”,”g”,”h”,”i”);$number_array = array(“1″,”2″,”3”);$changed_array = array_splice($character_array,1,3,$number_array); // will hold the element like: array(“e”,”1″,”2″,”3″,”i”);

shuffle

This function has the array as an argument to lớn change the position of its value in a random manner.

array_chunk

array_chunk() is used khổng lồ break an array inkhổng lồ the specified length of chunks.

$character_array = array(“e”,”f”,”g”,”h”,”i”);$chunks = array_chunk($character_array,2);//$chunks will be as follows/*Array ( => Array ( => e => f) => Array ( => g => h) => Array ( => i))*/

merge

merge function, is for joining one or more arrays into a single array.

$color_array1 = array(“Red”,”Blue”,”Green”);$color_array2 = array(“Yellow”,”Brown”);// returns array(“Red”,”Blue”,”Green”,”Yellow”,”Brown”);$color_array = array_merge($color_array1,$color_array2);

array_key_exists

This function is used to check whether the given key exists in the array or not. This function takes a key element and the input đầu vào array as arguments.

array_keys, array_values

These two functions will return the keys & values of an input đầu vào array, respectively. The following code shows the usage method of these functions and the resultant array of keys và values.

$student_array = array(“name”=>”Martin”,”mark”=>”90″,”grade”=>”A”);$key_array = array_keys($student_array) // returns array(“name”,”mark”,”grade”)$value_array = array_values($student_array) // returns array(“Martin”,”90″,”A”)

array_push, array_pop, array_shift, array_unshift

array_push() is used to push values inkhổng lồ an array. Using this function, a new element will be added to lớn the over of a given input đầu vào array.

The array_pop() is used khổng lồ get the last element of the array.

The array_shift() and the array_unshift() methods are as similar as array_push() and array_pop()But, the insert & retrieve sầu operations are performed at the starting position of the array.

extract, compact

The compact() is used khổng lồ convert the variable into lớn an array, whereas, the extract() is used to extract an array & convert the element of that array as variables.

The example shows it as follows. The second và third argument of extract() is optional. It is used khổng lồ add a prefix to lớn the variable name.

$student_array = array(“name”=>”Martin”,”mark”=>”90″,”grade”=>”A”);extract($student_array,EXTR_PREFIX_ALL,”student”); eđến $student_name . “-” . $student_mark . “(” . $student_grade . “)”; // prints as Martin – 90(A)$compact_array = compact(“student_name”,”student_mark”,”student_grade”); // will size an array