CodeIgniter Forums
How to identify if an array has been defined? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How to identify if an array has been defined? (/showthread.php?tid=24234)



How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]Unknown[/eluser]
Hi,

I am getting data from a table and storing it in an array as follows. I run this code based on certain condition.
Code:
if(condition is true)
  $data['Agent'] = $this->db->get('Table Name');

Then, I am using this array to display as follows:
Code:
foreach($Agent as $item)
{
    echo $item['field_name'];
}

This code works fine when the condition is true because in that case my array 'Agent' is defined. However, if the condition is false, my array 'Agent' is not defined and therefore the second piece of code does not work and gives an error message "Message: Undefined variable: Agent".

I would like to first check if my array has been defined and only then display the data. Please help!


How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]cahva[/eluser]
Code:
if (isset($Agent))
{
    foreach ($Agent as $item)
    {
        echo $item['field_name'];
    }
}



How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]andrewtheandroid[/eluser]
Hi efinanceweb the query result will return an array. if the array is empty there are no results so you just need to check if the resulting array is empty by using the count() or sizeof() function.

$query = $this->db->get('tablename');
$data = $query->result_array();

count($data)

is that what you mean?


How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]Unknown[/eluser]
Hi cahva. Your solution worked perfectly. Thanks a lot.


How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]BrianDHall[/eluser]
You can also use the empty function, which works on arrays as you would expect it would (an empty array is, predictably, empty, but if it is not set at all it will still return in an expected fashion and not throw any errors):

Code:
if (empty($data['agent']))
{
foreach..

Be careful of isset(), because a variable containing an empty string, or null, or an array with no elements, or an array element that is set but contains nothing, will all returning true as being 'set'.


How to identify if an array has been defined? - El Forum - 11-03-2009

[eluser]Phil Sturgeon[/eluser]
isset(), !empty(), is_array() will all help here.