Granit Zhubi
Granit Zhubi

Reputation: 63

How to check if an array is empty in PHP(Codeigniter)

Here it's my sample of code :

public function show($imei,$start_time,$end_time,$dateto) { 

    $from_time = str_replace('-','/',$start_time);
    $fromi=strtotime($from_time . ' ' . $end_time);
    $too1=strtotime($from_time . ' ' . $dateto); 

    $data['coordinates'] = $this->road_model->get_coordinatesudhetime($imei, $fromi, $too1);
    $this->load->view('road/show', $data);

                if (!empty($data))
        {
    echo 'Array it's empty*';
        }
     }

I want to check when $data it's empty .

Upvotes: 2

Views: 30169

Answers (3)

Deen
Deen

Reputation: 47

In your code, you are checking if the $data array is empty after loading it with coordinates from the model. However, you are checking it immediately after loading the view, which means the $data array will never be empty at that point. Instead, you should check if the array is empty before trying to use it. Here's an updated version of your code:

public function show($imei, $start_time, $end_time, $dateto) { 
    $from_time = str_replace('-', '/', $start_time);
    $fromi = strtotime($from_time . ' ' . $end_time);
    $too1 = strtotime($from_time . ' ' . $dateto); 

    $data['coordinates'] = $this->road_model->get_coordinatesudhetime($imei, $fromi, $too1);

    if (empty($data['coordinates'])) {
        echo 'Array is empty';
    } else {
        $this->load->view('road/show', $data);
    }
}

In this updated code, I've changed the condition to check if $data['coordinates'] is empty before loading the view. This way, you'll be able to handle the case when the array is empty before trying to use it in the view.

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

if (empty($data))
{
    echo "array is empty";
}
else
{
    echo "not empty";
} 

or count($data) returns the size of array.

If you are not sure about the variable being an array, you can check type and then size.

if(is_array($data) && count($data)>0)

Upvotes: 7

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can do this way also

if(is_array($data) && count($data)>0)
{
   echo "not empty";
}else{
   echo "empty";
}

Upvotes: 3

Related Questions