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


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

Then, I am using this array to display as follows:
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!

if (isset($Agent))
    foreach ($Agent as $item)
        echo $item['field_name'];

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();


is that what you mean?

Hi cahva. Your solution worked perfectly. Thanks a lot.

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):

if (empty($data['agent']))

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'.

[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.