Explode with name indexes (associative)

8

How can I make a explode in a variable where I can then access it by nominal index , and not by numeric index ?

Follow the example to get clearer:

<?php

// Aqui acesso pelo índice
$user = "Diego:25:RJ";
$info = explode(":",$user);
echo "O nome é ".$info[0];

?>

Instead of using:

echo "O nome é ".$info[0];

I would like to use:

echo "O nome é ".$info["nome"];

In my actual example, I would solve a certain situation in which the insertion or removal of certain information could be poor in use with the use of numeric index.

    
asked by anonymous 25.08.2016 / 18:15

5 answers

6

In addition to alternatives with explode , you can use preg_match . Just enter the nominal indices in the rule itself.

$string = 'Diego:25:RJ';
preg_match('/(?P<nome>\w+):(?P<idade>\d+):(?P<estado>\w+)/', $string , $matches );


echo $matches['nome'];
echo $matches['idade'];
echo $matches['estado'];

Example no ideone

    
26.08.2016 / 03:22
10

You can do with array_combine to associate each key with the corresponding value:

$user = "Diego:25:RJ";
$keys = array('nome', 'idade', 'estado');
$info = array_combine($keys, explode(":",$user));
print_r($info); // Array ( [nome] => Diego [idade] => 25 [estado] => RJ ) 

This way you should be sure to have the same number of keys ( $keys ) and values ( explode(":",$user) )

    
25.08.2016 / 18:20
7

It is the same logic as that of @Miguel, (which already received my +1), I just post to propose a rearrangement in the structure, in case it will vary the amount of data depending on the occasion:

$user = 'Diego:25:RJ';
$keys = 'Nome:Idade:Estado';

$info = array_combine( explode( ':', $keys ), explode( ':', $user ) );
print_r($info);

See working at IDEONE .


It's worth noting that if you restructure your data as JSON, it can get much simpler:

$json = '{"Nome":"Diego","Idade":25,"Estado":"RJ"}';
print_r( json_decode( $json, true ) );

Output

Array
(
    [Nome] => Diego
    [Idade] => 25
    [Estado] => RJ
)

See working at IDEONE .

    
25.08.2016 / 20:06
4
  

This response is based on the comment from @stderr !

You can use list (see example " Using list () with array indexes .)

$user = "Diego:25:RJ";

list($info['nome'], $info['idade'], $info['estado']) = explode(':', $user);

echo $info['nome'].' tem '. $info['idade'] .' anos e mora no estado do '.$info['estado'];

Result:

Diego tem 25 anos e mora no estado do RJ

See link

    
26.08.2016 / 15:46
3

You can do this using array()

$user = "Diego:25:RJ";
$info = explode(":",$user);
echo "O nome é ".$info[0];

$infoArr = array('nome'=>$info[0], 'idade'=>$info[1], 'estado'=>$info[2]);

print_r($infoArr); 
echo $infoArr['nome'];

Return:

Array
(
    [nome] => Diego
    [idade] => 25
    [estado] => RJ
)
O nome e Diego
    
25.08.2016 / 18:18