In a repetitive structure are there differences between working with Object or Array?

4

When I query the database by PHP and want to return that data with while , I usually use fetch_object() , which returns the data in type object .

For example:

$query = "SELECT * FROM TABELA";
$exect = $conn->query($query);

while($row = $exect->fetch_object()){
    echo $row->coluna.'<br>';
}

But before that I used fetch_array() to return data.

$query = "SELECT * FROM TABELA";
$exect = $conn->query($query);

while($row = $exect->fetch_array()){
    echo $row['coluna'].'<br>';
}

In these two cases some questions arise:

1 - Is there a performance difference?

2 - Is there any usability difference?

    
asked by anonymous 14.12.2015 / 12:03

1 answer

2

Essentially the difference is in the type of data that will be returned even. Use whatever is most convenient for your style or need.

fetch_array will return, obviously an array , which can be accessed by index or field name, or by both. This is set in the resulttype parameter and the default is access in both ways.

fetch_object can be accessed with the object access syntax of an object. It can populate an object of a specific class. This can be passed as a parameter.

In terms of performance they are essentially equivalent, because there are no actual objects in PHP, they are associative arrays from beneath the cloths. As it is an extra abstraction layer, it is likely to be slightly slower, but the difference will be tiny.

Of course there may be other problems with fetch_object , after all it will convert the contents of the key to a PHP identifier. There are rules of what can be contained in identifiers. What happens if I have any unsuitable PHP character in the database field name? You have to protect yourself from this with {} , the syntax gets worse.

If you want to automate member access through variables, you will also have to use this feature on objects. It is more natural to use array that works best with variables to indicate the key / index to be accessed. This is a very common standard for optimized code, follow the DRY principle and likes to make the language work for him and not him working for language.

Some people find that turning everything into an object is easier to work with. But they do not know that deep down they are not adding any advantage, neither performance nor organization, nothing. I just like it. So choose one or the other by taste.

    
14.12.2015 / 13:20