PHP Arrays in Brief: Create, Sort, Search and Transform

Quick Summary
- Create arrays with square brackets, add an item with $array[] = $value, read the first or last one with array_key_first() or array_key_last(), and combine arrays with the ... spread operator or array_merge().
- Search with in_array() or array_search() plus true for a strict comparison, compare array_search() results with false !==, and on PHP 8.4 use array_find(), array_any() or array_all() with a callback.
- array_map(), array_filter() and array_reduce() take arrow functions (fn) or callables like ucfirst(...); array_filter() keeps the original keys, so wrap it in array_values() before a for loop or json_encode().
A PHP array is an ordered list of values, each stored under a key. Numbered keys (0, 1, 2 …) make an indexed array; named keys make an associative array. Create one with square brackets, add an item with $array[] = $value, and use PHP’s array functions to slice, sort, search, compare and transform it. The examples run on PHP 8.2 and 8.4; the ones that need a newer version say so.
Create an array and loop through it
$studentDetails = array(
"Nahid",
"Mahamud",
8247,
"DRMC"
);
//this is fine too
$studentDetails2 = [
"Nahid",
"Mahamud",
8247,
"DRMC"
];
$n = count($studentDetails);
for( $i=0; $i<$n; $i++ ){
echo $studentDetails[$i]."\n";
}array() and [] create the same thing; the short [] form is the one you’ll see in current code. The for loop works because the keys run from 0 to count() - 1. A foreach loop, shown further down, works whatever the keys are.
Change a value
To change a value, assign a new one to its index:
$studentDetails[1] = "Hridoy"; //will replace Mahamud with HridoyGet the first and last item
array_key_first() and array_key_last() (PHP 7.3 and later) return the first and last key without changing the array. Use them to read the first or last value:
$studentDetails = [ "Nahid", "Mahamud", 8247, "DRMC" ];
echo $studentDetails[ array_key_first( $studentDetails ) ]; // Nahid
echo "\n";
echo $studentDetails[ array_key_last( $studentDetails ) ]; // DRMC
echo "\n";
echo count( $studentDetails ); // 4: nothing was removed
echo "\n";
var_dump( array_key_last( [] ) ); // NULL for an empty arrayPHP 8.5 adds array_first() and array_last(), which return the value directly, or null for an empty array. Unlike reset() and end(), array_key_first() and array_key_last() don’t move the array’s internal pointer.
Remove the last item: array_pop()
Array Pop removes the last item from an array and returns it.
$last_item = array_pop($studentDetails);
echo $last_item."\n";Remove the first item: array_shift()
Array Shift removes the first item from an array and returns it. The remaining numeric keys are renumbered from 0.
$first_item = array_shift($studentDetails);
echo $first_item."\n";Add an item to the end: array_push()
Add new data at the end of the array.
//array_push(arrayname,data);
array_push($studentDetails,'CSE');For a single item, $studentDetails[] = 'CSE'; does the same without a function call, and it’s what the PHP manual recommends. array_push() is handy when you add several items at once: array_push( $studentDetails, 'CSE', 'EEE' ).
Add an item to the start: array_unshift()
Add new data at the start of the array.
//array_unshift(arrayname,data);
array_unshift($studentDetails,'Male');Associative arrays
An associative array uses named keys instead of numbered indexes.
$myDetails = [
'First Name'=>'Nahid',
'Last Name'=>'Mahamud',
'College No'=>'8247'
];
echo $myDetails['College No'];Loop through an associative array
$foods = [
'vegetables' => 'capsicum, carrot, potato, radish',
'fruits' => 'apple, orange, banana, grape',
'drinks' => 'water, smoothie, juice',
];
echo "\n";
//show one data
echo $foods['vegetables'];
echo "\n";
//show all data
foreach ( $foods as $key => $value ) {
echo $key."=".$value."\n";
}
//another way
$keys = array_keys($foods);
print_r($keys); //use to print arrayConvert a string to an array and back: explode() and join()
//STRING TO ARRAY
$language = explode(', ','bangla, english, german');
var_dump($language);
echo $language[2];
echo "\n";
//ARRAY TO STRING
$languageString = join(', ',$language);
echo $languageString;join() is an alias of implode(), the name most code uses. The separator you pass to explode() must match the text exactly: split 'a, b' on ',' and the second item keeps its leading space.
Multidimensional arrays
//MULTIDIMENSIONAL ARRAY
$foods = [
'vegetables' => explode(', ','capsicum, carrot, potato, radish'),
'fruits' => explode(', ','apple, orange, banana, grape'),
'drinks' => explode(', ','water, smoothie, juice'),
];
echo "\n";
print_r($foods);
echo $foods['fruits'][1]; // orangeCombine arrays: spread, array_merge() and +
The spread operator ... unpacks one array into another (PHP 7.4 for numeric keys, PHP 8.1 for string keys). array_merge() gives the same result, and + follows different rules:
$frontend = [ 'html', 'css' ];
$backend = [ 'php', 'mysql' ];
$skills = [ ...$frontend, ...$backend, 'git' ];
print_r( $skills ); // html, css, php, mysql, git with keys 0 to 4
$defaults = [ 'color' => 'blue', 'size' => 'medium' ];
$chosen = [ 'size' => 'large' ];
print_r( [ ...$defaults, ...$chosen ] ); // color => blue, size => large
print_r( array_merge( $defaults, $chosen ) ); // the same: later string keys win
print_r( $chosen + $defaults ); // size => large, color => blue
print_r( [ 1 => 'a' ] + [ 1 => 'b', 2 => 'c' ] ); // 1 => a, 2 => c
print_r( array_merge( [ 1 => 'a' ], [ 1 => 'b', 2 => 'c' ] ) ); // 0 => a, 1 => b, 2 => carray_merge() and spread renumber numeric keys, and a later string key overwrites an earlier one. + keeps the left array’s keys and only adds missing ones, which suits “my settings plus the defaults”.
Convert an array to JSON and back
$stdDetails = [
'First Name'=>'Nahid',
'Last Name'=>'Mahamud',
'College No'=>'8247'
];
$jsonData = json_encode($stdDetails);
echo "\n";
echo $jsonData;
$jsonDataDecode = json_decode($jsonData,true);
echo "\n";
print_r ($jsonDataDecode);The second argument, true, makes json_decode() return an associative array instead of an object. An array with the keys 0, 1, 2 … becomes a JSON array ([…]); any other array becomes a JSON object ({…}).
Copy an array by value or by reference
$person = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
];
$newperson = $person;//copy by value: a separate array
/**
* A REFERENCE: BOTH NAMES POINT TO THE SAME ARRAY
*/
$newperson = &$person;//copy by reference -> changes value in both arrays
$newperson['lname'] = 'Hridoy';
print_r ($newperson);
print_r ($person);A plain assignment copies the array, so changing the copy leaves the original alone. With &, both variables are the same array, which is why both lines print Hridoy.
Remove an item from an associative array: unset()
Use unset() to remove data from an associative array by its key.
$person = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
];
print_r($person);
unset($person['lname']);
print_r($person);unset() works on indexed arrays too, but it leaves a gap in the keys (0, 2, 3 …). Wrap the array in array_values() if you need the keys renumbered.
Extract part of an array: array_slice()
Use array_slice() to extract part of an indexed or associative array. The original array stays unchanged.
/**
* extract data from an array
*/
$prDetails = [
"Nahid",
"Mahamud",
8247,
"DRMC",
];
//$extractedData = array_slice($prDetails,2);
/**
* array_slice(array_name, from where to slice, how many items)
* true, preserve offset key of the actual array
*/
$extractedData = array_slice($prDetails,2,1,true);
print_r($extractedData);
/**
* EXTRACT DATA FROM ASSOCIATIVE ARRAY
*/
$personx = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
'collegeNo' => 8247,
'homeTown' => 'Tangail',
'gender' => 'Male'
];
$personExtractData = array_slice($personx,2,null,true);
print_r($personExtractData);Remove and replace items: array_splice()
array_splice() removes items from the original array and returns them. Its optional fourth argument is a replacement: the second call uses it to insert new items where the removed ones were. The inserted items get numeric keys.
/**
* array_splice()-> extract and remove data from an array
*/
$personRemoveData = array_splice($personx,2,2);
print_r($personRemoveData);
/**
* array_splice()-> extract and remove data from an array
* and then insert some data
*/
$personx2 = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
'collegeNo' => 8247,
'homeTown' => 'Tangail',
'gender' => 'Male'
];
$newInfo = [
'hobby' => 'coding',
'position' => 'CEO',
];
$personDataUpdated = array_splice($personx2,2,2,$newInfo);
print_r($personDataUpdated);
print_r($personx2);Sort an array
/**
* SORT IN ARRAY
* sort() DOES NOT PRESERVE KEYS
* Use asort() in order to preserve key
* arsort() -> use in case you need reverse sort
* ksort() -> use in case you need sorting based on key
* krsort() -> use in case you need reverse sorting based on key
*/
$favFruits = ['apple','banana','orange','favOne'=>'guava','lichi','mango'];
asort($favFruits);
print_r($favFruits);
sort($favFruits);
print_r($favFruits);
$randu = ['apple','Alpine','anaconda','Banana','Ballon','cat','Cow','zoo','Giraffe'];
sort($randu);
print_r($randu);
//sort based on string and case insensitive
sort($randu, SORT_STRING | SORT_FLAG_CASE);
print_r($randu);The sort functions change the array itself and return true, so write sort( $randu );, not $randu = sort( $randu );. By default, capital letters sort before lowercase ones, which is why Alpine comes first until you add SORT_FLAG_CASE. Since PHP 8.0, sorting is stable: items that compare as equal keep their original order.
To sort by your own rule, for example a list of records by one field, use usort() with the spaceship operator <=>, which returns -1, 0 or 1:
$people = [
[ 'name' => 'Nahid', 'age' => 30 ],
[ 'name' => 'Bruce', 'age' => 25 ],
[ 'name' => 'Tony', 'age' => 30 ],
];
usort( $people, fn( $a, $b ) => $a['age'] <=> $b['age'] );
echo implode( ', ', array_column( $people, 'name' ) ); // Bruce, Nahid, TonyNahid stays ahead of Tony because both are 30 and sorting is stable. array_column() pulls one field out of every record.
Search an array for a value or a key
/**
* search in array
*/
$randu = ['apple','Alpine','anaconda','b'=>'Banana','Ballon','cat','zoo','Giraffe'];
if(in_array('zoo',$randu)){
echo "HURRAY!!! WE GOT IT";
}else {
echo "NOT FOUND";
}
echo "\n";
$searchPosition = array_search('zoo',$randu);
echo "We found it at key ".$searchPosition;
echo "\n";
/**
* search key in array
*/
if( key_exists('bx',$randu) ){
echo "KEY EXISTS";
} else {
echo "Key Not Found";
}key_exists() is an alias of array_key_exists(), the name you’ll usually see. Three things catch people out when searching:
$randu = [ 'zoo', 'apple', 'cat' ];
if ( array_search( 'zoo', $randu ) ) {
echo "found\n";
} else {
echo "not found?\n"; // printed: 'zoo' is at key 0, and 0 counts as false
}
$key = array_search( 'zoo', $randu );
if ( false !== $key ) {
echo "found at key $key\n"; // found at key 0
}
$codes = [ '1e1', '10', 'abc' ];
var_dump( in_array( 10, $codes ) ); // true: '1e1' == 10 in a loose comparison
var_dump( in_array( 10, $codes, true ) ); // false: no int 10 in the array
$settings = [ 'logo' => null ];
var_dump( isset( $settings['logo'] ) ); // false: the value is null
var_dump( array_key_exists( 'logo', $settings ) ); // true: the key existsarray_search()returns the key, which can be0, orfalsewhen nothing is found. Always compare withfalse !==.in_array()andarray_search()compare loosely unless you passtrueas the third argument. PHP 8 made loose comparison safer (0 == 'abc'is false now), but numeric strings still match numbers.isset()is false for a key whose value isnull;array_key_exists()only checks the key.
Find items with a callback: array_find() and array_any() (PHP 8.4)
PHP 8.4 added four functions that search with a callback. They stop calling it as soon as the answer is known, so they replace loops and array_filter() calls that only needed one result:
// PHP 8.4 and later
$products = [
[ 'name' => 'Shirt', 'price' => 25, 'stock' => 4 ],
[ 'name' => 'Cap', 'price' => 12, 'stock' => 0 ],
[ 'name' => 'Mug', 'price' => 9, 'stock' => 12 ],
];
$cheap = array_find( $products, fn( $p ) => $p['price'] < 15 );
echo $cheap['name'], "\n"; // Cap: the first match
echo array_find_key( $products, fn( $p ) => 'Mug' === $p['name'] ), "\n"; // 2
var_dump( array_any( $products, fn( $p ) => 0 === $p['stock'] ) ); // true: at least one
var_dump( array_all( $products, fn( $p ) => $p['price'] > 5 ) ); // true: every one
var_dump( array_find( $products, fn( $p ) => $p['price'] > 100 ) ); // NULL: no matchOn PHP 8.3 and older these functions don’t exist (“Call to undefined function array_find()”), so check the PHP version your server runs before you use them.
Compare arrays: array_intersect() and array_diff()
/**
* Identify common element in array
*/
$ourNumber1 = [1,2,33,4,567,12,13,221,233];
$ourNumber2 = [11,122,31,04,567,112,123,221];
$common =array_intersect($ourNumber1,$ourNumber2);
print_r($common);
$ourFruit1 = ['a'=>'apple', 'b'=>'banana','l'=>'lemon','o'=>'orange'];
$ourFruit2 = ['a'=>'apricot', 'b'=>'banana','LM'=>'lemon','o'=>'olive'];
$commonf =array_intersect($ourFruit1,$ourFruit2);
print_r($commonf);
//ALSO CHECK WITH KEY
$commonf2 =array_intersect_assoc($ourFruit1,$ourFruit2);
print_r($commonf2);
/**
* CHECK DIFFERENCE IN AN ARRAY
*/
$diff = array_diff($ourFruit1,$ourFruit2);
print_r($diff);
//also check diff with key
$diff = array_diff_assoc($ourFruit1,$ourFruit2);
print_r($diff);The results keep the keys of the first array. 04 in the second list is an octal literal, which is the number 4, so 4 is one of the common values.
Callback functions: array_walk(), array_map(), array_filter() and array_reduce()
array_map() and array_filter() return a new array and leave the original unchanged.
/**
* UTILITY FUNCTIONS OF ARRAY
* array_walk() -> runs a function on every item
*/
$unumber = [1,23,2,22,11,3,32,12,11,8,47];
//will show square of all elements
function numberSquare($num) {
printf("Square of %d is %d \n",$num, $num*$num);
}
/**
* UTILITY FUNCTIONS OF ARRAY
* array_map() -> returns a new array with the results
*/
//will return cube
function numberCube($num) {
return $num*$num*$num;
}
array_walk($unumber,'numberSquare');
$newArray = array_map('numberCube', $unumber);
print_r($newArray);
/**
* UTILITY FUNCTIONS OF ARRAY
* array_filter() -> returns a new array with the items that pass
*/
//check even
function checkEven( $n ) {
$edata = (($n % 2) == 0) ? true:false;
return $edata;
}
//check odd
function checkOdd( $n ) {
$edata = (($n % 2) !== 0) ? true:false;
return $edata;
}
//here checkEven is a callback function
//here checkOdd is a callback function
$newArray = array_filter($unumber,'checkEven');
$newArray2 = array_filter($unumber,'checkOdd');
print_r($newArray);
print_r($newArray2);
/**
* you can read a string's characters like an array
*/
$personName = ['clerk','bruce','banner','barry','kal','tony'];
//check name by b
function checkNameByb( $name ){
return $name[0] == 'b';
}
$nameWithb = array_filter($personName,'checkNameByb');
print_r($nameWithb);
/**
* ARRAY UTILITY FUNCTION
* array_reduce -> will do operation on an array then will reduce it
*/
$rnumber = [1,2,3,4];
/**
* this function will show sum
*/
function sum($oldVal, $newVal) {
return $oldVal+$newVal;
}
/**
* this function will show sum of even numbers
*/
function sumEven($oldVal, $newVal) {
if( $newVal % 2 == 0 ){
return $oldVal+$newVal;
} else{
return $oldVal;
}
}
$sum = array_reduce($rnumber,'sum'); //sum is callback function
$sumE = array_reduce($rnumber,'sumEven'); //sumEven is callback function
echo $sum;
echo "\n";
echo $sumE;$sum is 10 and $sumE is 6. For short callbacks you don’t need a named function: an arrow function (fn, PHP 7.4 and later) fits on one line, and the first-class callable syntax ucfirst(...) (PHP 8.1 and later) turns an existing function into a callback:
$unumber = [1,23,2,22,11,3,32,12,11,8,47];
$even = array_filter( $unumber, fn( $n ) => $n % 2 === 0 ); // same result as checkEven
$cubes = array_map( fn( $n ) => $n ** 3, [ 1, 2, 3 ] ); // 1, 8, 27
$sum = array_reduce( [ 1, 2, 3, 4 ], fn( $carry, $n ) => $carry + $n, 0 ); // 10
$names = [ 'clerk', 'bruce', 'banner' ];
print_r( array_map( ucfirst(...), $names ) ); // Clerk, Bruce, BannerThe third argument of array_reduce() is the starting value; without it the first call receives null.
Why does array_filter() leave gaps in the keys?
array_filter() keeps the original keys, so the even numbers above keep the keys 2, 3, 6, 7 and 9. That matters when you loop with for or send the result as JSON:
$unumber = [1,23,2,22,11,3,32,12,11,8,47];
$even = array_filter( $unumber, fn( $n ) => $n % 2 === 0 );
echo json_encode( $even ), "\n"; // {"2":2,"3":22,"6":32,"7":12,"9":8}
var_dump( array_is_list( $even ) ); // bool(false)
$even = array_values( $even );
echo json_encode( $even ), "\n"; // [2,22,32,12,8]
var_dump( array_is_list( $even ) ); // bool(true)array_values() renumbers the keys from 0. array_is_list() (PHP 8.1 and later) tells you whether an array’s keys are already 0, 1, 2 … in order.
Assign items to variables with list()
/**
* LIST FUNCTION IN ARRAY
*/
$studentDetails = [
"Nahid",
"Mahamud",
8247,
"DRMC",
];
list( $firstName, $lastName, $collegeNo, $college ) = $studentDetails;
echo $college;The short form with square brackets does the same, can skip items and can read named keys:
$studentDetails = [ "Nahid", "Mahamud", 8247, "DRMC" ];
[ $firstName, $lastName ] = $studentDetails;
[ , , , $college ] = $studentDetails;
echo "$firstName $lastName, $college\n"; // Nahid Mahamud, DRMC
$person = [ 'fname' => 'Nahid', 'lname' => 'Mahamud' ];
[ 'fname' => $fname, 'lname' => $lname ] = $person;
echo "$lname, $fname\n"; // Mahamud, Nahid
$a = 1;
$b = 2;
[ $a, $b ] = [ $b, $a ]; // swap two values
echo "$a $b\n"; // 2 1Create a range of numbers with range()
/**
* RANGE FUNCTION AND STEPPING IN ARRAY
*/
//will print 1 to 20
$numberRange = range(1,20);
/**
* range(first,last,step)
*/
$numberRangeEven = range(2,20,2);
print_r($numberRange);
print_r($numberRangeEven);Shuffle an array and pick a random item
shuffle() puts the items in random order and replaces the keys with numbers, even in an associative array. array_rand() returns a random key.
/**
* ARRAY SHUFFLE
* normally will not preserve key in associative array
*/
$personx = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
'collegeNo' => 8247,
'homeTown' => 'Tangail',
'gender' => 'Male'
];
shuffle($personx);
print_r($personx);
/**
* WILL SHOW A RANDOM VALUE FROM AN ARRAY
*/
$personxr = [
'fname' => 'Nahid',
'lname' => 'Mahamud',
'collegeNo' => 8247,
'homeTown' => 'Tangail',
'gender' => 'Male'
];
$key = array_rand($personxr);
echo $personxr[$key];
/**
* another way
* make a temporary array
*/
$_personxr = $personxr;
shuffle($_personxr);
print_r($_personxr);shuffle() and array_rand() are fine for display order, but the PHP manual warns they aren’t cryptographically secure. When the result must be unguessable, for example a prize draw or a random code, use Random\Randomizer (PHP 8.2 and later), which uses the secure engine by default:
$personxr = [ 'fname' => 'Nahid', 'lname' => 'Mahamud', 'homeTown' => 'Tangail' ];
$randomizer = new \Random\Randomizer();
print_r( $randomizer->shuffleArray( $personxr ) ); // a shuffled copy with new keys 0, 1, 2
$keys = $randomizer->pickArrayKeys( $personxr, 1 );
echo $personxr[ $keys[0] ]; // one random valueRemove empty and duplicate values
This example collects Advanced Custom Fields (ACF) values in a loop, removes duplicates with array_unique(), drops empty values with array_filter() and renumbers the keys with array_values().
$wp_day[] = get_field( 'w_day' ); //acf field values -> from foreach loop to an array
$unique_dates = array_unique($wp_day); //make the array unique
$unique_dates = array_values(array_filter($unique_dates)); //remove empty valuesWithout a callback, array_filter() removes every value that counts as false: '' and null, but also 0 and the string '0'. If 0 is a real value in your data, pass a callback that only removes the empty ones:
$wp_day = [ 'Monday', '', 'Monday', 'Friday', '0', null ];
print_r( array_values( array_filter( array_unique( $wp_day ) ) ) );
// Monday, Friday
print_r( array_values( array_filter( array_unique( $wp_day ), fn( $d ) => null !== $d && '' !== $d ) ) );
// Monday, Friday, 0Related articles
- splitting and joining strings in PHP: the string side of explode() and join()
- PHP’s eight data types: arrays next to the other seven types
- unpacking an array into function arguments: the … operator with a variadic function

