How to create a new WordPress array ?

So you have a set of data stored in an array and you want to put aside or create a new array with certain data.

There is a powerful function called wp_list_pluck() and wp_list_filter() that can be used for such tasks with any sort of datasets.

For example consider the following array:

$allUsers = array(
    array(
        'id' => 1,
        'user_name' => 'praveen',
        'email' => 'ravan@example.com',
        'type' => 'admin',
        'status' => 'active',
    ),
    array(
        'id' => 2,
        'user_name' => 'dinesh_silwani',
        'email' => 'silwani@example.com',
        'type' => 'guest',
        'status' => 'disabled',
    ),
    array(
        'id' => 3,
        'user_name' => 'ronak',
        'email' => 'ronak@example.com',
        'type' => 'host',
        'status' => 'disabled',
    ),
    array(
        'id' => 4,
        'user_name' => 'ravi',
        'email' => 'ravi@example.com',
        'type' => 'guest',
        'status' => 'disabled',
    ),
    array(
        'id' => 5,
        'user_name' => 'gopal',
        'email' => 'gopal@example.com',
        'type' => 'host',
        'status' => 'active',
    ),
);

First of all we are going to use wp_list_pluck() with 2 parameters, the array to pluck and the key to be plucked. So to create another array that contains just the key for the “user_name” we would do the following:

$allUserName = wp_list_pluck($allUsers, 'user_name'); // New array with all user names.
// would produce the following
// array('praveen', 'dinesh_silwani', 'ronak', 'ravi', 'gopal');

The same could be done to collate the id’s for later loops:

$allIDs = wp_list_pluck($allUsers, 'id');
// would produce the following
// array('1', '2', '3', '4', '5');

Now we are moving to another function. wp_list_filter() is another useful and powerful function that can be used to further refine your new array, say for instance you’d like to create a new array with just guest that are disabled, this is how you can go about it:

$filter_to_use = array('type' => 'guest', 'status' => 'disabled');
$allGuest = wp_list_filter($allUsers, $filter_to_use); // $allUsers = "all disabled guest user."
// this would end up creating an array like so
// array(
//    array(
//        'id' => 2,
//        'user_name' => 'dinesh_silwani',
//        'email' => 'silwani@example.com',
//        'type' => 'guest',
//        'status' => 'disabled',
//    ),
//    array(
//        'id' => 4,
//        'user_name' => 'ravi',
//        'email' => 'ravi@example.com',
//        'type' => 'guest',
//        'status' => 'disabled',
//    )
//);

Both of these functions are very useful when is comes to creating new arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *