5. Arrays Flashcards
How do you append a value to an array?
$arr[] = “Appended”;

What 2 functions can you use to get the size of an array?
count()
sizeof()
How can you pad an array with values?
array_pad($arr, min_elements, pad_value)
The min_elements can be a negative value as well, it will pad to the LEFT instead of RIGHT.

How can you copy array values to a list of variables?
list($first, $second) = $array
You can skip elements by just leaving that spot empty
Ex. list($first, , $third) = $array

How can you slice an array?
array_slice($arr, startIndex, numElements)

How can you split an array into multiple smaller arrays?
array_chunk($arr, arr_size)
This will return an array of arrays of the size you specified. There’s also an optional parameter to preserve keys which could be useful for associative arrays.

How can we list the keys of an array?
array_keys($arr)

How can we retrieve JUST the values from an array all in one function?
array_values($array)

How can you cut values out of an array and store in new array?
array_splice($array, start, length)

How do you create variables from an associative array?
extract($array)

How do you create an array from values?
Think inverse of creating variables from an array.
compact(“var1”, “var2”, ..etc)

How can you write a foreach loop for each element in an array?
foreach($array as $key => $value)
You can omit $key if you don’t need it.

How would you use a for loop on an array?
$arrayCount = count($array);
for ($i = 0; $i < $arrayCount; $i++)
Best to move the count outside of the for statement.

How can you call a function for each element in an array?
array_walk($array, “functionToCall”, “extraDataPassToFunction”)

How do you apply a function to each element in an array to turn it into a single value?
array_reduce($array, “functionToCall”, $initialValue)
functionToCall should take $runningTotal & $currentValue
