Replace list () by putting value in each index of an array

3

So I was browsing through php.net when I came across List () and went to see what it was for. Then they gave me the following example:

$info = array('Café', 'marrom', 'cafeína');
list($bebida, $cor, $substancia) = $info;
echo "$bebida é $cor e $substancia o faz especial.\n";

In this one I ask myself: Do not give me, instead of doing it, do type:

$info = [$bebida, $cor, $substancia]; 
aí fazer tipo 
$info[0] = "café"
$info[1] = "marrom"
$info[2] = "cafeína" 

And then just call a echo of life type "$info[0] é $info[1] e $info[2] o faz especial. \n" ??

    
asked by anonymous 14.03.2017 / 14:16

2 answers

2

The capacity of the list function goes much further. There is the ability to handle arrays greater, in more specific cases that your code will depend on. I consider that list , in addition to being used and abused, has the ability to leave the code more semantic.

Your example would be more semantic if:

<?php
$frase = "café marrom cafeina";
list($bebida, $cor, $substancia) = explode(" ", $frase);

if ($cor == 'marrom') {
    $cor = 'preto';
}

echo sprintf("%s é %s e %s o faz especial.", $bebida, $cor, $substancia);

So, let's agree that $info[1] has to go back up in code, interpret array , and then understand that the 1 key is actually a variable with the cor attribute. So, the code loses the chance to be more understandable.

My example is not one of the best, but my intention with the answer is to tell you that not only do you have a more "common" way of doing things, that the medium is the best to use. Research, study, investigate, mature your code.

    
14.03.2017 / 14:57
2

The list command creates a list of variables in a single, simple operation, which is a facilitator when programming, but nothing prevents you from using each position of array to print value, such as you did it in the example.

These are possible ways to develop with , it's a lot times useful in certain scenarios, such as everything in system development.

This command can also be used for array array or simples .

Simple Array:

$info0 = array('um', 'dois');
list($a1,$a2) = $info0;
echo $a1; // um
echo $a2; // dois

Two-dimensional arrays:

$info1 = array(array('versao', 'forma'), array('razão', 'cultura'));
list($b0, $b1) = $info1;
var_dump($b0); //    
//array(2) {
//  [0]=>
//  string(6) "versao"
//  [1]=>
//  string(5) "forma"
//}
var_dump($b1); //
//array(2) {
//  [0]=>
//  string(6) "razão"
//  [1]=>
//  string(7) "cultura"
//}

that is, it extracts from every position from bidimensionais to array simple to make it easier to encode your variáveis .

It is always good to know the alternatives and often giving maintenance in third-party code do not be surprised at this type of coding .

References:

14.03.2017 / 14:52