Cara menggunakan php replace keys
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 code readable and short. Show Also, there is a presentation with given code examples, so you can download it from the related links and show it to your colleagues to build a stronger team. The BasicsThere are two different ways of creating arrays. One is to use First, the key always has to be unique. If you try to 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] => Apple [2] => 20 [3] => -18 [4] => Monkey ) */ $second = [10, "Apple", 20, -18, "Monkey"]; print_r($second); /* Array ( [0] => 10 [1] => Apple [2] => 20 [3] => -18 [4] => Monkey ) */ $third = [10, 5 => "Apple", 2 => 20, -18, "Monkey"]; print_r($third); /* Array ( [0] => 10 [5] => Apple [2] => 20 [6] => -18 [7] => Monkey ) */ As you can see, using either You also don't need to specify a key for every array value. When left out, PHP sets the key to
one more than the largest specified integer key. All automatically assigned keys will be greater than or equal to 0. Working With Keys and ValuesLet's start with the basic functions that work with array keys and values. One of them is $keys = ['sky', 'grass', 'orange']; $values = ['blue', 'green', 'orange']; $array = array_combine($keys, $values); print_r($array); // Array // ( // [sky] => blue // [grass] => green // [orange] => orange // ) You should know that the
print_r(array_keys($array)); // ['sky', 'grass', 'orange'] print_r(array_values($array)); // ['blue', 'green', 'orange'] print_r(array_flip($array)); // Array // ( // [blue] => sky // [green] => grass // [orange] => orange // ) You can check if an array contains a specific value and get its first
corresponding key using the $values = ["Apples", "Bananas", "Mangoes", "100", "200"]; if(in_array(100, $values)) { echo '100 is one of the values'; } // 100 is one of the values if(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); // 3 echo 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 to look up multiple elements in an array, it's usually faster to check if it contains a particular value by first flipping the array with Make Your Code ShorterThe // 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 $string = 'hello|wild|world'; list($hello, , $world) = explode('|', $string); echo("$hello, $world"); // hello, world Also, $arrays = [[1, 2], [3, 4], [5, 6]]; foreach ($arrays as list($a, $b)) { $c = $a + $b; echo($c . ', '); // 3, 7, 11, } With the $array = [ 'clothes' => 't-shirt', 'size' => 'medium', 'color' => 'blue', ]; extract($array); echo("$clothes $size $color"); // t-shirt medium blue Be aware that The opposite of the previous function is the $clothes = 't-shirt'; $size = 'medium'; $color = 'blue'; $array = compact('clothes', 'size', 'color'); print_r($array); // Array // ( // [clothes] => t-shirt // [size] => medium // [color] => blue // ) Filtering FunctionsThere is a great function for array filtering, and it is called $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 to filter not only by the values. You can use Also, you can call $numbers = [-1, 0, 1]; $not_empty = array_filter($numbers); print_r($not_empty); // [0 => -1, 2 => 1] You can get only unique values from an array using the $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 = [ ['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, $cinemas = Cinema::find()->all(); $cinema_ids = array_column($cinemas, 'id'); // php7 forever! Walking Through the ArraysUsing $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 to 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 use $fruits = [ 'banana' => 'yellow', 'apple' => 'green', 'orange' => 'orange', ]; array_walk($fruits, function(&$value, $key) { $value = "$key is $value"; }); print_r($fruits); // Array // ( // [banana] => banana is yellow // [apple] => apple is green // [orange] => orange is orange // ) Joining the ArraysThe best way to merge two or more
arrays in PHP is to use the $array1 = ['a' => 'a', 'b' => 'b', 'c' => 'c']; $array2 = ['a' => 'A', 'b' => 'B', 'D' => 'D']; $merge = array_merge($array1, $array2); print_r($merge); // Array // ( // [a] => A // [b] => B // [c] => c // [D] => D // ) To remove array values from another array (or arrays), use $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 ValuesUse $numbers = [1, 2, 3, 4, 5]; echo(array_sum($numbers)); // 15 echo(array_product($numbers)); // 120 echo(array_reduce($numbers, function($carry, $item) { return $carry ? $carry / $item : 1; })); // 0.0083 = 1/2/3/4/5 To count all the values of an array, use $things = ['apple', 'apple', 'banana', 'tree', 'tree', 'tree']; $values = array_count_values($things); print_r($values); // Array // ( // [apple] => 2 // [banana] => 1 // [tree] => 3 // ) Generating ArraysTo generate an array with a given size and the same value, use $bind = array_fill(0, 5, '?'); print_r($bind); // ['?', '?', '?', '?', '?'] To generate an array with a range of keys and 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 $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
to generate an associative array with different keys and the same value assigned to each key, you can simply use the $keys = ["Apples", "Bananas", "Mangoes"]; $fruit_count = array_fill_keys($keys, 100); print_r($fruit_count); /* Array ( [Apples] => 100 [Bananas] => 100 [Mangoes] => 100 ) */ Sorting ArraysIt is good to remember that every sorting function in PHP works with arrays by a reference and returns true on success or false on failure. There's a basic
sorting function called
You can see the combinations of these letters in the following table:
Combining Array Functions Like a BossThe real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with $values = ['say ', ' bye', ' ', ' to', ' spaces ', ' ']; $words = array_filter(array_map('trim', $values)); print_r($words); // ['say', 'bye', 'to', 'spaces'] To create an id to a title map from an array of models, we can use a combination of $models = [$model1, $model2, $model3]; $id_to_title = array_combine( array_column($models, 'id'), array_column($models, 'title') ); To get the top three values of an array, we can use $letters = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']; $values = array_count_values($letters); // get key to count array arsort($values); // sort descending preserving key $top = array_slice($values, 0, 3); // get top 3 print_r($top); // Array // ( // [d] => 5 // [a] => 4 // [b] => 2 // ) It's easy to use $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 ConclusionAs you can see, knowledge of the main array functions can make your code much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations to use with extra parameters and flags, but I think that in this tutorial we've covered the basics that every PHP developer should know. Learn PHP With a Free Online CourseIf you want to learn PHP, check out our free online course on PHP fundamentals! In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database. Did you find this post useful? Kyiv, Ukraine I adore automation, API integration, and the software as a service delivery model. To further my aspiration of making a better web, I combine proper prototyping, insightful design, and reliable code. As a web developer, I mostly use PHP, JavaScript, and Linux shell to reach these goals. |