Forum Moderators: coopster

Message Too Old, No Replies

check between normal array and object-array?

         

carsten888

12:09 pm on Nov 16, 2010 (gmt 0)

10+ Year Member



I got a function in which I need to check if the array parsed to it is a normal-array or a object-array (the kind that you pull from a database). To be able to read the id's parsed in the arrays correctly.

<?php 
function do_that($array){
$counter = 0;
foreach($array as $key => $row){
if($array_type=='object'){
$id = $array->id;
}else{
$id = $array[$counter];
}

//do stuff with id

$counter = $counter+1;
}
}
?>


I tried is_array and is_object, but that retruns true for both kind of arrays.

How to check between a normal-array and a object-array?

enigma1

8:00 pm on Nov 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



is_array and is_object are the recommended functions to distinguish between the 2 (there is gettype but is not good idea).

For example with mysql if you use mysql_fetch_object you will get back an object, if you use mysql_fetch_array you will get back an array.

$array_type is not defined anywhere, why not checking the input of the do_that function at the beginning instead of iterating?

function do_that($input){
if( is_object($input) ) {
$input = (array)$input;
}
foreach($input as $key => $value ) {
// process
}
}

carsten888

2:31 pm on Nov 17, 2010 (gmt 0)

10+ Year Member



why not checking the input of the do_that function at the beginning

yes, could do that, but in the example I also wanted to show why I want to distinguise between the 2 (to get the row's id).

is_object

does not work, because when normal array it also returns true.

enigma1

2:38 pm on Nov 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



is_object works as expected here is sample code to try it and convert it to an array.


class testobj {
function testobj() {
$this->id = 0;
$this->data = 1;
}
}

function check($input){
echo 'Is this an Array? <b>' . (is_array($input)?'true':'false') . '</b><br />';
if( is_object($input) ) {
// convert to array
$input = (array)$input;
}
print_r($input);
}

$to = new testobj;
check($to);
$to = array(1,2,3);
check($to);
exit();

carsten888

6:44 am on Nov 18, 2010 (gmt 0)

10+ Year Member



your test-object is not a object based array.

enigma1

9:23 am on Nov 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



what you mean is not? It is treated like an array using the array cast. If you mean an array of objects vs an array of values then they're both arrays.