Array Helper
Array Helper – Codeigniter Array Helper file contains the functions which are used for arrays. You can load this helper and use it’s functions. Here in this tutorial we are going to explain how you can load array helper in codeigniter and use it’s functions. We will also explain how you can load helper on view file and use it’s functions. You can use our online editor to run and see the output of the example.
Array Helper in Codeigniter
Let us go step by step to understand the codeigniter array helper.
Load Array Helper in Codeigniter
You can load the array helper using the following syntax –
Load Array Helper in Codeigniter Example :
$this->load->helper('array'); |
Let us go through the available
Array Helper Functions
There are following functions available in the codeigniter Helper.
Element
Syntax :
element($item, $array[, $default = NULL]) |
Parameters –
- $item – Item to fetch from array.
- $array – Input array.
- $default – Default value to be returned if array is not valid.
Returns –
Returns NULL on failure. Returns item on success.
This function is used to fetch an item from array. This functions checks the index and its value. If the index value exists it returns the value else it returns NULL or the specified value in third parameter $default.
Example –
Codeigniter Array Helper function – element: Example
<?php $array = array( 'id' => 901, 'sku' => 'red-bounce', 'color' => 'gray', 'price' => '' ); echo element('id', $array); // will return 901 echo element('price', $array); // return null echo element('price', $array, '$99'); // return $99 ?>` |
Elements
Syntax :
elements($items, $array[, $default = NULL]) |
Parameters –
- $items – Array of Items to fetch from array.
- $array – Input array.
- $default – Default value to be returned if array is not valid.
Returns –
Returns NULL on failure. Returns items on success.
This function is used to fetch multiple items from an array. This functions checks the index and value of each array item is set or not. If the index value exists it returns the value else it returns NULL or the specified value in third parameter $default.
Example –
Codeigniter Array Helper function – element: Example
<?php $array = array( 'id' => 901, 'sku' => 'red-bounce', 'color' => 'gray', 'price' => '' ); echo elements(array('id','sku'), $array); // will return array('id'=>901, 'sku'=>'red-bounce'); echo elements(array('id','sku', 'price'), $array); // will return array('id'=>901, 'sku'=>'red-bounce', 'price'=>NUll); echo elements('price', $array, '$99'); // return array('id'=>901, 'sku'=>'red-bounce', 'price'=>$99); ?>` |
Random Element
This returns the random element from the specified array.
Syntax :
random_element($array) |
Where $array is input array.
Example
Syntax :
$array = array(1, 100, 21, 34, 589, 90, 192); echo random_element($array); // will give any random number |
Advertisements