PHP arrays are an essential data structure used to store multiple values in a single variable. Arrays are particularly useful for transforming complex calculations into simpler solutions. In this guide, we will explore how to declare an array in PHP, the different types of PHP arrays, and various array functions in Php. We will also learn how to iterate through arrays using foreach
loops, and understand the usage of powerful functions like array_filter
, in_array
, and array_map()
. Additionally, we’ll cover how to perform array to string conversion in PHP.
Lets dive into this tutorial.
What is Array in Php ?
An array is a data structure which can be used to store elements of similar or different data types in a single variable . For example if you want to store person data which contains name,email,age and salary .So for storing these type of data we can use array.In a single array data we can store these different data types.
First we need to declare or define an array . To define an array in Php we can use array() function or we can use brackets [] .The elements we need to store in array is defined inside the array() function or inside brackets [] .
Example of Array in Php
$person=array('name'=>'Ram','age'=>10,'email'=>'ram@phpguruacademy.com','salary'=>'100.00');
In this example $person variable is defined .This variable holds different elements with values of different data types.It holdsname which is string,age which is integer,email which is string and slary which is float.
Types of Php Array
Php provides three main types of Array .They can be summarised as below:
1.Indexed Arrays
2.Associative Arrays
3.Multidimensional Arrays
Indexed Arrays
Arrays which has values stored using numeric indexes are known as indexed arrays. In these arrays we donot have to explicitly define indexes.They are by default defined here.
Example :
$person_name =array('Ram','Shyam',Rita');
echo $person_name[0];
//Output
Ram
In the above example $person_name is a indexed array .In this array the names are stored in array() function.They are by default mapped to indexes in ascending order. The statement echo $person_name[0] displays Ram as output as here in array in ‘0’ index Ram is stored.
Associative Arrays
Arrays where indexes are not numeric instead they are named keys .They are useful when we want to store key value pairs as data.
Example:
$marks=array('name'=>'Ram','marks'=>'100');
In this above example $marks is a variable which is used to store key value pair data. In this variable name and maks keys are used to store values .
Multi-dimensional Arrays
Arrays which holds more than one arrays inside as elements to store data are known as multi dimensional arrays.These arrays are helpful to handle complex data which are tabular data or matrices data.
Example:
$person_data=[
["name" => "Alia", "age" => 21],
["name" => "Dimple", "age" => 26],
["name" => "Deepika", "age" => 29],
];
echo $person_data[0]['name'];
In this example above $person_data variable stores multiple person records with name and age .To print the name of person in first array $person_data[0][‘name’] is used.The 0 index identifies that it’s first array and with name key we can access the person name.
To handle multiple data in multi dimensional array we cannot manually use 0 or 1 index .We need to iterate the arrays .SO we can do this by using foreach loop.
For example the above code can be simplified using foreach loop. Check theeample below:
foreach($person_data as $data){
echo $data['name'];
}
//Output
Alia
Dimple
Deepika
In the above example $person_data is iterated and which displays all the name in each row.
Array Functions in Php
PHP provides a rich set of array functions to handle and manipulate arrays effectively. Here’s a list of commonly used array functions in PHP, categorized for easy understanding:
Creating and Modifying Arrays
array()
: Function to define a blank array.array_push($array, $value)
: This function is used to add elements to the end of an array.array_pop($array)
: This function removes the last element from an array and returns it .array_unshift($array, $value)
: This function add elements in an array at the beginningarray_shift($array)
: This function removes the first element from an array and returns it .array_merge($array1, $array2)
: This function join two or more than two arrays together .array_slice($array, $offset, $length)
: This function slices a part from an array.array_splice($array, $offset, $length, $replacement)
: This function replaces a part in an array.
Searching and Filtering
in_array($value, $array)
: This function checks if the provided argument exists as value in an array or not.array_search($value, $array)
: This function returns key for the value provided as argument here .array_filter($array, $callbackfunction)
: This function uses a callback function to filters elements in an array.array_key_exists($specifickey, $array)
: This function checks that array contains the specific key provided as an argument here.
Transforming Arrays
array_map($callbackfunction, $array)
: This function add a callback function for each element of an array.array_reduce($array, $callbackfunction)
: This function by using a callback function reduces an array to a single value .array_values($array)
: using a callback returns all the values of an array.array_keys($array)
: using a callback returns all the keys of an array.array_combine($keys, $values)
: using a callback combines two array to convert it into an associative array.
Sorting
sort($array)
: This function sorts an array by values in an ascending order .rsort($array)
: This function sorts an array by values in descending order.asort($array)
: This function sorts an associative array by values in an ascending order It preserves keys while sorting.ksort($array)
: This function sorts by keys an associative array in ascending order .usort($array, $callback)
: This function sorts an array using a user-defined comparison function.
Other Useful Functions
array_reverse($array)
:This function Reverses the order of an array.array_sum($array)
: This function finds the sum of all values in an array .array_unique($array)
: This function removes duplicate values within an array.array_column($array, $column_key)
: This function returns all single column values within a multidimensional array.array_diff($array1, $array2)
: This function find differences between two arrays by comparing them.array_intersect($array1, $array2)
: This function finds the values by intersecting two arrays.
These functions allow you to efficiently create, modify, search, sort, and manipulate arrays in PHP, making them essential tools for PHP developers.
Array to String Conversion in Php
An array can be converted to string using different methods . The most common methods to convert array to string are –
1.Using implode : Array can be converted to string using php inbuilt function implode .An array can be converted to a string by joining its elements with a specified delimiter.implode function can be used to convert only one dimensional arrays.
Example:
$array_elements=array('rama','rita','raja','rana');
implode(',',$array_elements);
//Output
rama,rita,raja,rana
2.Using json_encode() : json_encode() function can be used to convert multi dimensional structured array to string .
Example:
$array_elements = ["name" => "Rama", "age" => 30];
$jsonDataString = json_encode($array_elements);
echo $jsonDataString;
// Output
{"name":"Rama","age":30}
The json_encode data is used in applications where we need to return data in json format like in APIs responsse data or while communicating with ajax data using Php .
3.Serialize : Serialize function can be used to convert array to serialized string which can later be deserialized back into an array using unserialize()
.
Example:
$array_elements = ["a1" => 10, "a2" => 20];
$serializedData = serialize($array_elements);
echo $serializedData ;
// Output:
a:2:{s:1:"a1";i:10;s:1:"a2";i:20;}
Serialization is used to store complex structured data (like arrays or objects) in a database in a predefined format that can be easily saved as a string and later reconstructed or fetched and unserialized when needed.
So in this guide we learned what arrays are i PHp and how to define them.We also learn what are different types of arrays and functions in php.With this we can convert any complex code to simple structure using arrays . So you can use the functions defined here in your APIs to return encodeed data or you can serialize data and store data in database as per your requirements.
Happy Coding!