PHP array types and values

Asked

Viewed 444 times

0

How I turn that kind of data $pessoas->nome for $pessoas['nome'] and vice versa with php and because they are different?

  • If the long explanation is plausible, here it is: http://answall.com/a/82251/4995

5 answers

6


You can change the typing by using (array).

$pessoas = new stdClass;
$pessoas->nome = 'Papa Charlie';
$pessoas = (array) $pessoas;


//output: Array( [nome] => Papa Charlie )
print_r( $pessoas );


// output: Papa Charlie
echo $pessoas['nome'];

The reverse process by changing the typing using (object).

$pessoas = array( 'nome' => 'Papa Charlie' );
$pessoas = (object) $pessoas;


// output: stdClass Object( [nome] => Papa Charlie )
print_r( $pessoas );


// output: Papa Charlie
echo $pessoas-> nome;

See an example on Ideone.

  • you can also cast at the time of the declaration: $people = (Object)array( 'name' => 'Papa Charlie' );

  • @Danielomine, yes, but I believe he needs the data as array, and only at some given time is it necessary to use the Object.

3

The $pessoas->nome indicates that people are an object. Already $pessoas['nome'] indicates an array. You can transform the names present in objects into arrays (as long as they are not static) using the function get_object_vars( object $object ).

Read more about objects on http://php.net/manual/en/language.oop5.php

  • http://ideone.com/f6NBYL kkk

  • ?? @Ivanferrer did not understand the relevance of showing Ideone’s phpinfo() result...

  • I had updated the output to make a test... but the code was another thing I had put... look again.

  • right, but I still don’t understand your point of view. Look at this one: http://ideone.com/MyiLGP

  • It’s not my point of view, it’s just a demonstration of get_object_vars()

  • ah tá :) pardon

  • If you have any point of view, it’s just the mood we’re already used to, so we make a complex method just to give a way out of "Hello World".

  • Here is an example of this: http://ideone.com/J3Iilc

Show 3 more comments

2

Array vs Objects

That "little arrow" there $pessoas->nome is the Object Separator. He is responsible for access to members belonging to an object (whether property or method).

In the first case $pessoas->nome, the objeto could be any class. In PHP, the default object is stdClass.

You can use the var_dump in this case to know the name of the class from which the object originates.

In the case of $pessoas['nome'] you are accessing the members of a array in PHP.

So, look at these examples to be able to fix better:

Example of Array

$array = array('nome' => 'wallace');

echo $array['nome']; // Imprime: 'wallace'

Example of objeto (stdClass);

$object = new stdClass;

$object->nome = 'Wallace';

echo $object->nome; // Imprime: 'wallace';

get_class($object); // Imprime: 'stdClass'

Arrayaccess interface

There are cases where you can use both shapes, both for objects and for arrays. This happens in any class that implements the interface ArrayAccess.

PHP defaults to a class that implements ArrayAccess, which is the ArrayObject (see what more demonstrative name!)

Behold:

$arr_and_obj = new ArrayObject();

$arr_and_obj->nome = 'wallace';

$arr_and_obj['idade'] = 25;

echo $arr_and_obj->nome; // Imprime: 'wallace';

echo $arr_and_obj['idade']; // Imprime: 25

In this case, only classes that implement this interface accept this "double access form". In other cases, an error will be generated:

Behold:

$obj = new stdClass;

$obj[1];

Exit:

Cannot use Object of type stdClass as array

Conversion between types

As quoted in the @Ivanferrer reply, you can convert these types.

Object to array:

$obj = new stdClass;

$obj->nome = 'wallace';

var_dump((array)$obj);

Array for object:

$obj = (object) array('nome' => 'Wallace');

These two forms quoted above are called cast.

There is also another conversion were, which is through the function settype.

Behold:

$object = new stdClass;

settype($object, 'array');

var_dump($object); // Imprime: Array(0){}

2

With "arrow" you are referencing the attribute of an object (Object), with brackets, you are referencing the key of the matrix (array). To switch the typing, you would have to force the typing or do a "cast":

class Test {

public $valor = 'teste';

}

$objeto = new Test();

$array['valor'] = 'teste';

/* 1. a variável se torna um array $variavelArray['valor']
   2. O valor do atributo referenciado passará a ser
      tratado como array. */ 
$variavelArray  = (array) $objeto;
/* 1. a variável se torna um objeto $variavelObject->valor
   2. O valor do array passa a ser um atributo uma new StdClass; */
$variavelObject = (object) $array;

Here is an example: http://ideone.com/xgkA7x

In many cases, it is necessary to make this conversion, but there are people who do it as a "gambiarra" to solve problems that could be treated in a much more elegant way.

-4

If you use the class PDO php itself will have the options when making a query for example, you can use the:

PDO::FETCH_OBJ for object, in case it will be returned and access the attributes through the $pessoas->nome or using the PDO::FETCH_ASSOC returns in array form as $pessoas['nome'].

Follows the link

  • 4

    None element in the question suggests database! Every alternative is welcome, both for the community and for the AP, but as long as it’s within the scope of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.