Friday, November 13, 2015

Arrays: Pushes and Pops

Arrays can be a very helpful way of dealing with groups of data. There are a variety of ways of working with arrays through different programming languages, some more complex than others, some more functional, etc.

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_set
array_push($num_set, 5); // now array is [1,2,3,4,5]
Notice 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.
Pop example:
$num_set = [1,2,3,4];
array_pop($num_set); //$num_set is now [1,2,3]
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_shift example:
$num_set = [1,2,3,4];
array_shift($num_set); // now array is [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_unshift example:
$num_set = [1,2,3,4];
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];
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.

merge only example:
$random_1 = [38193, 83493, 11027, 34272];
$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
merge with sort example:
$books_1 = ["The Idiot", "Crime and Punishment", "War and Peace"];
$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.
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"

No comments:

Post a Comment