SlideShare une entreprise Scribd logo
1  sur  6
Useful functions for arrays in PHP

      Function                   Explanation                                 Example

sizeof($arr)         This function returns the number      Code:
                     of elements in an array.              $data = array("red", "green", "blue");

                     Use this function to find out how     echo "Array has " . sizeof($data) . "
                     many elements an array contains;      elements";
                     this information is most commonly     ?>
                     used to initialize a loop counter
                     when processing the array.            Output:
                                                           Array has 3 elements
array_values($arr)   This function accepts a PHP array     Code:
                     and returns a new array containing    $data = array("hero" => "Holmes", "villain"
                     only its values (not its keys). Its   => "Moriarty");
                     counterpart is the array_keys()       print_r(array_values($data));
                     function.                             ?>

                     Use this function to retrieve all the Output:
                     values from an associative array. Array
                                                           (
                                                           [0] => Holmes
                                                           [1] => Moriarty
                                                           )
array_keys($arr)     This function accepts a PHP array     Code:
                     and returns a new array containing    $data = array("hero" => "Holmes", "villain"
                     only its keys (not its values). Its   => "Moriarty");
                     counterpart is the array_values()     print_r(array_keys($data));
                     function.                             ?>

                     Use this function to retrieve all the Output:
                     keys from an associative array.       Array
                                                           (
                                                           [0] => hero
                                                           [1] => villain
                                                           )
array_pop($arr)      This function removes an element Code:
                     from the end of an array.        $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    Code:
                         the end of an array.                $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 Code:
                         from the beginning of an array.  $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   Code:
                          the beginning of an array.         $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     Code:
                   iteratively traverse an array. Each     $data = array("hero" => "Holmes", "villain"
                   time each() is called, it returns the   => "Moriarty");
                   current key-value pair and moves        while (list($key, $value) = each($data)) {
                   the array cursor forward one            echo "$key: $value n";
                   element. This makes it most             }
                   suitable for use in a loop.             ?>

                                                           Output:
                                                           hero: Holmes
                                                           villain: Moriarty

sort($arr)         This function sorts the elements of     Code:
                   an array in ascending order. String     $data = array("g", "t", "a", "s");
                   values will be arranged in              sort($data);
                   ascending alphabetical order.           print_r($data);
                                                           ?>
                   Note: Other sorting functions
                   include asort(), arsort(), ksort(),     Output:
                   krsort() and rsort().                   Array
                                                           (
                                                           [0] => a
                                                           [1] => g
                                                           [2] => s
                                                           [3] => t
                                                           )
array_flip($arr)   The function exchanges the keys         Code:
                   and values of a PHP associative         $data = array("a" => "apple", "b" =>
                   array.                                  "ball");
                                                           print_r(array_flip($data));
                   Use this function if you have a         ?>
                   tabular (rows and columns)
                   structure in an array, and you want Output:
                   to interchange the rows and         Array
                   columns.                            (
                                                       [apple] => a
                                                       [ball] => b
                                                       )
array_reverse($arr) The function reverses the order of Code:
                        elements in an array.                   $data = array(10, 20, 25, 60);
                                                                print_r(array_reverse($data));
                        Use this function to re-order a         ?>
                        sorted list of values in reverse for
                        easier processing—for example,          Output:
                        when you're trying to begin with        Array
                        the minimum or maximum of a set         (
                        of ordered values.                      [0] => 60
                                                                [1] => 25
                                                                [2] => 20
                                                                [3] => 10
                                                                )
array_merge($arr)       This function merges two or more        Code:
                        arrays to create a single composite     $data1 = array("cat", "goat");
                        array. Key collisions are resolved in   $data2 = array("dog", "cow");
                        favor of the latest entry.              print_r(array_merge($data1, $data2));
                                                                ?>
                        Use this function when you need
                        to combine data from two or more        Output:
                        arrays into a single structure—for      Array
                        example, records from two               (
                        different SQL queries.                  [0] => cat
                                                                [1] => goat
                                                                [2] => dog
                                                                [3] => cow
                                                                )
array_rand($arr)        This function selects one or more       Code:
                        random elements from an array.          $data = array("white", "black", "red");
                                                                echo "Today's color is " .
                        Use this function when you need         $data[array_rand($data)];
                        to randomly select from a               ?>
                        collection of discrete values—for
                        example, picking a random color         Output:
                        from a list.                            Today's color is red
array_search($search,   This function searches the values       Code:
$arr)                   in an array for a match to the          $data = array("blue" => "#0000cc", "black"
                        search term, and returns the            => "#000000", "green" => "#00ff00");
                        corresponding key if found. If more     echo "Found " . array_search("#0000cc",
                        than one match exists, the key of       $data);
                        the first matching value is             ?>
                        returned.
                                                                Output:
Use this function to scan a set of Found blue
                        index-value pairs for matches, and
                        return the matching index.
array_slice($arr,       This function is useful to extract a   Code:
$offset, $length)       subset of the elements of an array,    $data = array("vanilla", "strawberry",
                        as another array. Extracting begins    "mango", "peaches");
                        from array offset $offset and          print_r(array_slice($data, 1, 2));
                        continues until the array slice is     ?>
                        $length elements long.
                                                               Output:
                        Use this function to break a larger    Array
                        array into smaller ones—for            (
                        example, when segmenting an            [0] => strawberry
                        array by size ("chunking") or type     [1] => mango
                        of data.                               )
array_unique($data) This function strips an array of         Code:
                        duplicate values.                    $data = array(1,1,4,6,7,4);
                                                             print_r(array_unique($data));
                        Use this function when you need ?>
                        to remove non-unique elements        Output:
                        from an array—for example, when Array
                        creating an array to hold values for (
                        a table's primary key.               [0] => 1
                                                             [3] => 6
                                                             [4] => 7
                                                             [5] => 4
                                                             )
array_walk($arr, $func) This function "walks" through an       Code:
                        array, applying a user-defined         function reduceBy10(&$val, $key) {
                        function to every element. It          $val -= $val * 0.1;
                        returns the changed array.             }

                        Use this function if you need to       $data = array(10,20,30,40);
                        perform custom processing on           array_walk($data, 'reduceBy10');
                        every element of an array—for          print_r($data);
                        example, reducing a number series      ?>
                        by 10%.                                Output:
                                                               Array
                                                               ([0] => 9
                                                               [1] => 18
                                                               [2] => 27
                                                               [3] => 36
                                                               )
Useful functions for arrays in php

Contenu connexe

Tendances

Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)Zach Bray
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arraysKumar
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceAlexey Raga
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Stephen Chin
 
Using arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationUsing arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationNicole Ryan
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Lucas Witold Adamus
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212Mahmoud Samir Fayed
 

Tendances (20)

Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
02 arrays
02 arrays02 arrays
02 arrays
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)
 
Using arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationUsing arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing information
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Sparklyr
SparklyrSparklyr
Sparklyr
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
Fp java8
Fp java8Fp java8
Fp java8
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 

En vedette

25 php interview questions – codementor
25 php interview questions – codementor25 php interview questions – codementor
25 php interview questions – codementorArc & Codementor
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersVineet Kumar Saini
 
PHP Technical Questions
PHP Technical QuestionsPHP Technical Questions
PHP Technical QuestionsPankaj Jha
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answersiimjobs and hirist
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
Dropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPDropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPelliando dias
 
BUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSBUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSPRINCE KUMAR
 
Computer relative short from....
Computer relative short from....Computer relative short from....
Computer relative short from....Nimai Chand Das
 
Ejobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlEjobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlprabhat kumar
 
Lan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPLan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPAman Soni
 
Zend Php Certification Study Guide
Zend Php Certification Study GuideZend Php Certification Study Guide
Zend Php Certification Study GuideKamalika Guha Roy
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
Web School - School Management System
Web School - School Management SystemWeb School - School Management System
Web School - School Management Systemaju a s
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evoltGIMT
 

En vedette (20)

25 php interview questions – codementor
25 php interview questions – codementor25 php interview questions – codementor
25 php interview questions – codementor
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
PHP Technical Questions
PHP Technical QuestionsPHP Technical Questions
PHP Technical Questions
 
Practice exam php
Practice exam phpPractice exam php
Practice exam php
 
1000+ php questions
1000+ php questions1000+ php questions
1000+ php questions
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
lect4
lect4lect4
lect4
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Strings
StringsStrings
Strings
 
Dropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHPDropr - The Message Queue project for PHP
Dropr - The Message Queue project for PHP
 
BUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESSBUILDING WEBSITES ON WORDPRESS
BUILDING WEBSITES ON WORDPRESS
 
Computer relative short from....
Computer relative short from....Computer relative short from....
Computer relative short from....
 
Ejobportal project ppt on php my_sql
Ejobportal project ppt on php my_sqlEjobportal project ppt on php my_sql
Ejobportal project ppt on php my_sql
 
Lan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHPLan chatting and file transfer Project on PHP
Lan chatting and file transfer Project on PHP
 
Zend Php Certification Study Guide
Zend Php Certification Study GuideZend Php Certification Study Guide
Zend Php Certification Study Guide
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
PHP based School ERP
PHP based School ERPPHP based School ERP
PHP based School ERP
 
Web School - School Management System
Web School - School Management SystemWeb School - School Management System
Web School - School Management System
 
Php login system with admin features evolt
Php login system with admin features   evoltPhp login system with admin features   evolt
Php login system with admin features evolt
 

Similaire à Useful functions for arrays in php

Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJason Swartz
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavVyacheslav Arbuzov
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 
An example of R code for Data visualization
An example of R code for Data visualizationAn example of R code for Data visualization
An example of R code for Data visualizationLiang (Leon) Zhou
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
R Workshop for Beginners
R Workshop for BeginnersR Workshop for Beginners
R Workshop for BeginnersMetamarkets
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 

Similaire à Useful functions for arrays in php (20)

Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Chap 3php array part4
Chap 3php array part4Chap 3php array part4
Chap 3php array part4
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Array
ArrayArray
Array
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Scala
ScalaScala
Scala
 
arrays.pdf
arrays.pdfarrays.pdf
arrays.pdf
 
Tuples All the Way Down
Tuples All the Way DownTuples All the Way Down
Tuples All the Way Down
 
An example of R code for Data visualization
An example of R code for Data visualizationAn example of R code for Data visualization
An example of R code for Data visualization
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
R Workshop for Beginners
R Workshop for BeginnersR Workshop for Beginners
R Workshop for Beginners
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Php array
Php arrayPhp array
Php array
 

Useful functions for arrays in php

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