• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to identify if an array has been defined?

#1
[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!

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

#3
[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?

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

#5
[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'.

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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.