CI4 provides in built helpers for arrays. This helps us avoid writing most of the logic using the traditional for loops or while loops.
In this section, we will see three functions from array helpers.
We include the array helper using the helper function ie. helper(“array”)
- array_deep_search : This helps in searching the value for a given key in a deeply nested array. It is not necessary to know the structure of the array. we can simply pass the key and it will return the value for that key. Let’s look at an example.
namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
helper('array');
$user_info = [
'user' => [
'address' => [
'house_number' => 7,
'street' => "Bakers street",
'pincode' => 73301,
],
'profile' => [
'firstname' => "Sherlock",
'lastname' => "Holmes",
'age' => 35,
],
],
];
$age = array_deep_search("age",$user_info);
echo $age;
}
}
This will print the age as 35 in the above example. If the array has repetitive values for age, it will return the first one only.
2. array_flatten_with_dots : If the array is a multidimensional nested one and say you need a one dimensional array for ease of use, then this is the function to go for.
namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
helper('array');
$user_info = [
'user' => [
'address' => [
'house_number' => 7,
'street' => "Bakers street",
'pincode' => 73301,
],
'profile' => [
'firstname' => "Sherlock",
'lastname' => "Holmes",
'age' => 35,
],
],
];
$flattened_user_info = array_flatten_with_dots($user_info);
print_r($flattened_user_info);
}
}
The output for the above example will be
Array ( [user.address.house_number] => 7 [user.address.street] => Bakers street [user.address.pincode] => 73301 [user.profile.firstname] => Sherlock [user.profile.lastname] => Holmes [user.profile.age] => 35 )
This makes it more easier and readable as well. You can access the values using the dot notation.
3. dot_array_search : Although we can access the array values using the keys, even for a nested array; CI4 provides another way to access them using a dot notation. We can access the nested elements using the dot notation, instead of the keys in square brackets. If the key doesn’t exist, it returns NULL.
<?php
namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
helper('array');
$user_info = [
'user' => [
'address' => [
'house_number' => 7,
'street' => "Bakers street",
'pincode' => 73301,
],
'profile' => [
'firstname' => "Sherlock",
'lastname' => "Holmes",
'age' => 35,
],
],
];
$firstname = dot_array_search('user.profile.firstname', $user_info);
$lastname = dot_array_search('user.profile.lastname', $user_info);
echo $firstname." ".$lastname;
}
}
?>
This will output “Sherlock Holmes”.