Anton Bagaiev Oct 27, 2020 Read Time: 12 mins url-selector#selectionChanged"> Dansk Deutsch English Español Bahasa Indonesia Pусский Tiếng Việt In this tutorial, I am going to make a list of common PHP array functions, with examples of usage and best practices, Every PHP developer must know how to use them and how to combine array functions to make cod" /> Anton Bagaiev Oct 27, 2020 Read Time: 12 mins url-selector#selectionChanged"> Dansk Deutsch English Español Bahasa Indonesia Pусский Tiếng Việt In this tutorial, I am going to make a list of common PHP array functions, with examples of usage and best practices, Every PHP developer must know how to use them and how to combine array functions to make cod" />

Create Array Of Associative Arrays In Php, Working With Php Arrays In The Right Way

post-promotion-placement#checkSidebarAdDisplayCondition" data-controller="scroll-position sticky-ad post-promotion-placement ">
Anton Bagaiev Oct 27, 2020
Read Time: 12 mins url-selector#selectionChanged"> Dansk Deutsch English Español Bahasa Indonesia Pусский giờ đồng hồ Việt

In this tutorial, I am going lớn make a danh mục of common PHP array functions, with examples of usage và best practices. Every PHP developer must know how lớn use them và how to combine array functions to lớn make readable and short.

Bạn đang xem: Create array of associative arrays in php, working with php arrays in the right way

Also, there is a presentation with given examples, so you can download it from the related liên kết and show it khổng lồ your colleagues khổng lồ build a stronger team.

The Basics

There are two different ways of creating arrays. One is khổng lồ use array() to specify the elements as key-value pairs. The other method is lớn put all elements inside <>. There are two important points that you should remember when creating associate arrays with key pairs.

First, the key always has to be unique. If you try lớn use the same key multiple times in an array, PHP will ignore all other key-value pairs except the last one. Second, if a key is created as floats, bools, and valid string representations of integers, then it will be cast to integers.

Here are a few examples of creating arrays in PHP:

$first = array(10, "Apple", 20, -18, "Monkey");print_r($first);/* Array( <0> => 10 <1> => hãng apple <2> => trăng tròn <3> => -18 <4> => Monkey) */$second = <10, "Apple", 20, -18, "Monkey">;print_r($second);/* Array( <0> => 10 <1> => apple <2> => đôi mươi <3> => -18 <4> => Monkey) */$third = <10, 5 => "Apple", 2 => 20, -18, "Monkey">;print_r($third);/* Array( <0> => 10 <5> => táo bị cắn dở <2> => 20 <6> => -18 <7> => Monkey) */As you can see, using either array() or <> is equivalent when creating arrays. The shorthand notation has been available starting from PHP 5.4.

You also don"t need to specify a key for every array value. When left out, PHP sets the key lớn one more than the largest specified integer key. All automatically assigned keys will be greater than or equal to 0.

Working With Keys & Values

Let"s start with the basic functions that work with array keys & values. One of them is array_combine(), which creates an array using one array for keys & another for its values:

$keys = <"sky", "grass", "orange">;$values = <"blue", "green", "orange">;$array = array_combine($keys, $values);print_r($array);// Array// (// => blue// => green// => orange// )You should know that the array_values() function returns an indexed array of values, array_keys() returns an array of keys of a given array, and array_flip() exchanges keys with values:

print_r(array_keys($array)); // <"sky", "grass", "orange">print_r(array_values($array)); // <"blue", "green", "orange">print_r(array_flip($array));// Array// (// => sky// => grass// => orange// )You can kiểm tra if an array contains a specific value và get its first corresponding key using the array_search() function. You can also use in_array() if you just want to lớn know whether an array contains a specific element & are not interested in its position. Consider using the array_key_exists() function when you want to check if the array uses a given key.

Xem thêm: Phần Mềm Upload File Lên Host Ing Bằng Phần Mềm Ftp, Hướng Dẫn Upload Dữ Liệu Lên Hosting Bằng Winscp

$values = <"Apples", "Bananas", "Mangoes", "100", "200">;if(in_array(100, $values)) echo "100 is one of the values";// 100 is one of the valuesif(in_array(200, $values) !== false) echo "200 is not one of the values";// 200 is not one of the values$values = <"Apples", "Bananas", "Mangoes", "100", "200", 100>;echo array_search(100, $values);// 3echo array_search(100, $values, true);// 5$values = <"Apples" => 100, "Bananas" => 10, "Mangoes" => 45>;if(array_key_exists("Apples", $values)) echo "We have apples.";// We have apples.As the example above shows, make sure you use strict type checking if you don"t want any unexpected results.

If you want khổng lồ look up multiple elements in an array, it"s usually faster to kiểm tra if it contains a particular value by first flipping the array with array_flip() and then using array_key_exists().

Make Your Shorter

The list() function, which is not really a function but a language construction, is designed to assign variables in a short way. For example, here"s a basic example of using the list() function:

// define array$array = <"a", "b", "c">;// without list()$a = $array<0>;$b = $array<1>;$c = $array<2>;// with list()list($a, $b, $c) = $array;This construction works perfectly with functions like preg_slit() or explode() . Also, you can skip some parameters if you don"t need them to lớn be defined:

$string = "hello|wild|world";list($hello, , $world) = explode("|", $string);echo("$hello, $world"); // hello, worldAlso, list() can be used with foreach, which makes this construction even better:

$arrays = <<1, 2>, <3, 4>, <5, 6>>;foreach ($arrays as list($a, $b)) $c = $a + $b; echo($c . ", "); // 3, 7, 11, With the extract() function, you can export an associative array lớn variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:

$array = < "clothes" => "t-shirt", "size" => "medium", "color" => "blue",>;extract($array);echo("$clothes $size $color"); // t-shirt medium blueBe aware that extract() is not safe if you are working with user data (like results of requests), so it"s better to lớn use this function with the flags EXTR_IF_EXISTS and EXTR_PREFIX_ALL.

The opposite of the previous function is the compact() function, which makes an associative array from variables:

$clothes = "t-shirt";$size = "medium";$color = "blue";$array = compact("clothes", "size", "color");print_r($array);// Array// (// => t-shirt// => medium// => blue// )

Filtering Functions

There is a great function for array filtering, & it is called array_filter(). Pass the array as the first param & an anonymous function as the second param. Return true in a callback function if you want khổng lồ leave this element in the array, and false if you don"t:

$numbers = <20, -3, 50, -99, 55>;$positive = array_filter($numbers, function($number) return $number > 0;);print_r($positive); // <0 => 20, 2 => 50, 4 => 55>There is a way lớn filter not only by the values. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as a third parameter lớn pass the key or both value and key khổng lồ the callback function.

Also, you can call array_filter() without a callback lớn remove all empty values:

$numbers = <-1, 0, 1>;$not_empty = array_filter($numbers);print_r($not_empty); // <0 => -1, 2 => 1>You can get only quality values from an array using the array_unique() function. Notice that the function will preserve the keys of the first unique elements:

$array = <1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5>;$uniques = array_unique($array);print_r($uniques);// Array// (// <0> => 1// <4> => 2// <7> => 3// <8> => 4// <9> => 5// )With array_column(), you can get a danh sách of column values from a multi-dimensional array, like an answer from a SQL database or an import from a CSV file. Just pass an array & column name:

$array = < <"id" => 1, "title" => "tree">, <"id" => 2, "title" => "sun">, <"id" => 3, "title" => "cloud">,>;$ids = array_column($array, "id");print_r($ids); // <1, 2, 3>Starting from PHP 7, array_column() becomes even more powerful, because it is now allowed to work with an array of objects. So working with an array of models just became easier:

$cinemas = Cinema::find()->all();$cinema_ids = array_column($cinemas, "id"); // php7 forever!

Walking Through the Arrays

Using array_map(), you can apply a callback lớn every element of an array. You can pass a function name or anonymous function lớn get a new array based on the given array:

$cities = <"Berlin", "KYIV", "Amsterdam", "Riga">;$aliases = array_map("strtolower", $cities);print_r($aliases); // <"berlin", "kyiv, "amsterdam", "riga">$numbers = <1, -2, 3, -4, 5>;$squares = array_map(function($number) return $number ** 2;, $numbers);print_r($squares); // <1, 4, 9, 16, 25>There is a myth that there is no way to pass values and keys of an array khổng lồ a callback, but we can bust it:

$model = <"id" => 7, "name"=>"James">;$callback = function($key, $value) return "$key is $value";;$res = array_map($callback, array_keys($model), $model);print_r($res);// Array// (// <0> => id is 7// <1> => name is James// )But this looks dirty. It is better to lớn use array_walk() instead. This function looks the same as array_map(), but it works differently. First of all, an array is passed using a reference, so array_walk() doesn"t create a new array, but changes a given array. So as a source array, you can pass the array value using a reference in a callback. Array keys can also be passed easily:

$fruits = < "banana" => "yellow", "apple" => "green", "orange" => "orange",>;array_walk($fruits, function(&$value, $key) $value = "$key is $value";);print_r($fruits);// Array// (// => banana is yellow// => táo khuyết is green// => orange is orange// )

Joining the Arrays

The best way lớn merge two or more arrays in PHP is khổng lồ use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:

$array1 = <"a" => "a", "b" => "b", "c" => "c">;$array2 = <"a" => "A", "b" => "B", "D" => "D">;$merge = array_merge($array1, $array2);print_r($merge);// Array// (// => A// => B// => c// => D// )To remove array values from another array (or arrays), use array_diff(). Lớn get values which are present in given arrays, use array_intersect(). The next examples will show how it works:

$array1 = <1, 2, 3, 4>;$array2 = <3, 4, 5, 6>;$diff = array_diff($array1, $array2);print_r($diff); // <0 => 1, 1 => 2>$intersect = array_intersect($array1, $array2);print_r($intersect); // <2 => 3, 3 => 4>

Do the Math With Array Values

Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array_reduce():

$numbers = <1, 2, 3, 4, 5>;echo(array_sum($numbers)); // 15echo(array_product($numbers)); // 120echo(array_reduce($numbers, function($carry, $item) return $carry ? $carry / $item : 1;)); // 0.0083 = 1/2/3/4/5To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys và a count of these values as a value:

$things = <"apple", "apple", "banana", "tree", "tree", "tree">;$values = array_count_values($things);print_r($values);// Array// (// => 2// => 1// => 3// )

Generating Arrays

To generate an array with a given size and the same value, use array_fill():

$bind = array_fill(0, 5, "?");print_r($bind); // <"?", "?", "?", "?", "?">To generate an array with a range of keys & values, like hours in the day or letters, use range():

$letters = range("a", "z");print_r($letters); // <"a", "b", ..., "z">$hours = range(0, 23);print_r($hours); // <0, 1, 2, ..., 23>To get a part of an array—for example, just the first three elements—use array_slice():

$numbers = <1, 2, 3, 4, 5, 6, 7, 8, 9, 10>;$top = array_slice($numbers, 0, 3);print_r($top); // <1, 2, 3>If you ever want khổng lồ generate an associative array with different keys và the same value assigned to each key, you can simply use the array_fill_keys() function.

$keys = <"Apples", "Bananas", "Mangoes">;$fruit_count = array_fill_keys($keys, 100);print_r($fruit_count);/* Array( => 100 => 100 => 100) */

Sorting Arrays

It is good lớn remember that every sorting function in PHP works with arrays by a reference và returns true on success or false on failure. There"s a basic sorting function called sort(), and it sorts values in ascending order without preserving keys. The sorting function can be prepended by the following letters:

a, sort preserving keysk, sort by keysr, sort in reverse/descending orderu, sort with a user function

You can see the combinations of these letters in the following table:


Combining Array Functions lượt thích a Boss

The real magic begins when you start to lớn combine array functions. Here is how you can trim và remove empty values in just a single line of with array_filter() and array_map():

$values = <"say ", " bye", " ", " to", " spaces ", " ">;$words = array_filter(array_map("trim", $values));print_r($words); // <"say", "bye", "to", "spaces">To create an id khổng lồ a title map from an array of models, we can use a combination of array_combine() and array_column():

$models = <$model1, $model2, $model3>;$id_to_title = array_combine( array_column($models, "id"), array_column($models, "title"));To get the đứng đầu three values of an array, we can use array_count_values(), arsort(), and array_slice():

$letters = <"a", "a", "a", "a", "b", "b", "c", "d", "d", "d", "d", "d">;$values = array_count_values($letters); // get key to count arrayarsort($values); // sort descending preserving key$top = array_slice($values, 0, 3); // get top 3print_r($top);// Array// (// => 5// => 4// => 2// )It"s easy to use array_sum() and array_map() to calculate the sum of order in a few rows:

$order = < <"product_id" => 1, "price" => 99, "count" => 1>, <"product_id" => 2, "price" => 50, "count" => 2>, <"product_id" => 2, "price" => 17, "count" => 3>,>;$sum = array_sum(array_map(function($product_row) return $product_row<"price"> * $product_row<"count">;, $order));print_r($sum); // 250


As you can see, knowledge of the main array functions can make your much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations khổng lồ use with extra parameters & flags, but I think that in this tutorial we"ve covered the basics that every PHP developer should know.

Learn PHP With a không lấy phí Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!