I love how PHP works with arrays because it makes them easy to create and has some great functions for working with them. Pushes and pops are nice quick ways of adding or taking out members at the end of an array that many programming languages have. I'll be using PHP for my examples.
Push example:
$num_set = [1,2,3,4]; //creates array $num_setNotice that one of the unique things with PHP is that you don't have to declare your variables. PHP does the work in identifying what kind of variable it is by seeing what kind of data is stored in it. I find this quite convenient, though it has its drawbacks as well.
array_push($num_set, 5); // now array is [1,2,3,4,5]
Pop example:
$num_set = [1,2,3,4];But what if you wanted to deal with more than just the last member of an array? No problemo...that's where array_shift (similar to pop) and array_unshift (similar to push) come in...
array_pop($num_set); //$num_set is now [1,2,3]
array_shift example:
$num_set = [1,2,3,4];Note: This affects array keys and literal keys differently. The array keys shift with the array change while literal keys to not change.
array_shift($num_set); // now array is [2,3,4];
array_unshift example:
$num_set = [1,2,3,4];Sometimes it's helpful to merge two arrays together. Depending on the outcome you are looking for you may want to only do a merge, or you may want to also do a sort.
array_unshift($num_set, 0); // "0" is the index of the array (counting starts with 0 in many programming languages). Now array is [0,1,2,3,4];
merge only example:
$random_1 = [38193, 83493, 11027, 34272];merge with sort example:
$random_2 = [23115, 12372, 25168, 18307];
$random_all = array_merge($random_1, $random_2);
//result will be a combination of the two arrays with random_2 following random_1 in the order that they are represented
$books_1 = ["The Idiot", "Crime and Punishment", "War and Peace"];But what if you wanted "The Idiot" and "A Tale of Two Cities" to be sorted based on the second word rather than the first? Well, an easy way to accomplish this is to set your array up for such by putting the title in like: "Idiot, The" and "Tale of Two Cities, A"
$books_2 = ["Gulliver's Travels", "A Tale of Two Cities", "Pilgrim's Progress"];
$books_all = array_merge($books_1, $books_2);
//at this point the books would be ordered in the position they appear from the first array followed by the second array.
sort($books_all);
//now the books are listed alphabetically.
No comments:
Post a Comment