|
|
|---|
Array Operations in PHPIn this section we will see some most commonly used array functions, their usage with examples. Split an array into chunksTo split an array into smaller chunks or smaller sized arrays, we use array_chunk() function of PHP. This will return arrays of several smaller sizes and each array's index number will start with zero unless you want to use the preserve_keys parameter to preserve the original index numbers from the input array used. The syntax is:
array_chunk ( array input, int size [, bool preserve_keys] )
Using the above function in an example:
<?Combine an array with data elements and other with its keysWe can create an array by combining one array with keys and second array with corresponding data elements. Note that the number of keys and data elements in both the arrays has to be equal for this operation to be successful. We will make use of built-in function array_combine(). Its syntax is:
array_combine ( array keys, array values )
and the example using array_combine() is:
<?Merging two or more arraysUsing an built-in function array_merge() we can merge two or more arrays to form a single array. The values from the second array are appended at the end of first array and so on. So, if three arrays are to be merged, elements from third will be appended at the end of second array and then it will be appended at the end of the first array. Take a look at this syntax and example:
array_merge ( array array1 [, array array2 [, array ...]] )
<?Searching an arraySearching for a value in an array is made simple using the function array_search(). If the keyword is found in the array, then the corresponding key of that value is retured for further operations. The syntax and example are:
array_search ( keyword, array name )
<?With that example we wrap up our section on Arrays in PHP. If you feel there should be more content and examples or something else that should be on here, please contact us. |
|
|
|---|