How to write variables in PHP?

10

I was watching the videos of Robson V.Leite and I realized that at some point it retrieves information from the forms to insert into the database in a way different from the one I use, the only way I knew so far. It stores the variables in the form of indexes. Ex:

$f['titulo'] = $_POST['titulo'];
$f['conteudo'] = $_POST['conteudo'];
$f['data'] = $_POST['data'];

Why would it store the variables this way and not the way I've always used them? I do this:

$titulo = $_POST['titulo'];
$conteudo = $_POST['conteudo'];
$data = $_POST['data'];
    
asked by anonymous 17.11.2015 / 14:21

6 answers

17

You have to ask him. Maybe try to look at the context.

I, for example, do not usually do either (okay, some cases I do). Most do as in the second example because they learned to do so. One does not wonder why one is doing this. She often believes it is necessary to do it without question. Some rare cases believe that it is better to do so. It may be best if you will use the variable coming externally multiple times. But the improvement essentially is to write something simpler.

I actually do not understand why people love to create variables where they are not needed. This is everywhere. Someone did it wrong or for a very specific reason, then the other "programmers" are copying without trying to understand why that is done. There must be a reason to create a variable. In general this reason is that you really need to store a specific value that will be used multiple times. I even understand that it can give more readability, but if it will only be used once, it will not do any operations, the $_POST is of good size.

In the case of his code, it's also simpler, but it's so small, I think it's better not to do it. Either do the second way or leave the pattern.

Of course his code may be this way for some other reason that we do not know. But I will not speculate on this as in other answers, after all it's just speculation.

The fact is that:

  • There is no reason to do this in the context provided
  • If we speculate what he wants to do, we come to the conclusion that his teaching is bad for not presenting the points incrementally
  • If we try to guess the intent, we can not say that it would use the PDO parameter because the syntax is different. If you are going to have to change the syntax later, then why not change everything?

    And if you're going to use some function that expects an array , why not use $_POST itself? Why create another?

    Of course, handling external data is important in most cases, but the example is not doing this. And if you are going to do it, at the moment of collecting the data of $_POST is that the verification / sanitization should be done and there probably play in local variables. Even though it throws at another associative array, it is not yet being shown.

        
    17.11.2015 / 14:30
    10

    In addition to @bigown's response, it is really unnecessary to reassign names to the variable in this case.

    The main consideration is that the variable will have the same value .

    Most of the time, people do this in order to "simplify" the use of the variable. But that really is not necessary.

    The way you demonstrated in the example:

    $f['titulo'] = $_POST['titulo'];
    $f['conteudo'] = $_POST['conteudo'];
    $f['data'] = $_POST['data']; 
    

    It would be easier to do this:

    $f = $_POST;
    

    But would not give any advantage , as the title value, for example, will remain the same.

    The assignment of external variables (or any other type of variable to be treated) would be most useful if there were any treatment in their values.

    Example:

    $titulo = trim($_POST['titulo']);
    
    $conteudo = htmlentities(trim($_POST['conteudo']));
    

    Note that in the case above, the values will not be the same.

    Another very common case in using variables to "copy values" is in return of functions. Because instead of having to process everything again, it is better to save the value and reuse it.

    Example:

    function get_nome_cidade($cidade_id)
    {
        // Faz uma consulta na url externa
        // Faz um mapeamento complicado para filtrar os dados
    
       return $nome_da_cidade;
    }
    

    Here we could do:

     $cidade = get_nome_cidade(10);
    
     $banco->salva(['cidade' => $cidade]);
    
     echo "Ele salvou a cidade {$cidade}";
    

    Well, since the value of the function would always be the same, but the cost of obtaining it would be high, we might worry about saving it in a variable.

    Another factor that I would take into consideration is "giant names".

    Well it's better to do this:

     $nome = $_POST['usuario']['nome_completo_usuario']
    
     echo "O nome do usuário é {$nome}":
    

    What to do

    echo "O nome do usuário é {$_POST['usuario']['nome_completo_usuario']}"
    

    But in this case we can also consider that using big names is also a bad practice - maybe you'll forget the names, so big they are!

    And to complement it, there's nothing wrong with his way of doing things and his way. It's just unnecessary, in my opinion.

        
    17.11.2015 / 18:34
    10

    In spite of several good answers already existing here, I will put two reasons here that maybe are very strong for the use of this.

    But before I tell you that this is not an index but rather associative, the index uses numbers:

    $f['titulo'] = $_POST['titulo'];
    $f['conteudo'] = $_POST['conteudo'];
    $f['data'] = $_POST['data'];
    

    The likely reasons are:

    • Use php native functions

      If you use associative arrays, you can use various PHP functions to handle this data, for example:

      • array_​change_​key_​case , array_​chunk , array_​column , array_​combine , array_​count_​values , array_​diff_​assoc , array_​diff_​key , array_​diff_​uassoc , array_​diff_​ukey , array_​diff , array_​fill_​keys , array_​fill , array_​filter , array_​flip , array_​intersect_​assoc array_​intersect_​key , array_​intersect_​uassoc , array_​intersect_​ukey , array_​intersect , array_​key_​exists , array_​keys , array_​map , array_​merge_​recursive array_​merge , array_​multisort , array_​pad , array_​pop , array_​product , array_​push , array_​rand , array_​reduce , array_​replace_​recursive , array_​replace , array_​reverse , array_​search , array_​shift , array_​slice , array_​splice array_​sum , array_​udiff_​assoc , array_​udiff_​uassoc , array_​udiff , array_​uintersect_​assoc , array_​uintersect_​uassoc , array_​uintersect , array_​unique array_​unshift , array_​values , array_​walk_​recursive , array_​walk , arsort , asort , compact , count , current , extract , in_​array , key_​exists , key , krsort , ksort list , natcasesort , natsort , next , pos , prev , range , reset , rsort shuffle

      A good example is sizeof , with it it is possible to access all variables to do something with them, for example search all values that are possibly words and apply sort (it's a basic example only):

      function ucwords_array($n) {
          if (preg_match('#[a-z]#i', $n) > 0) {
              return $n;
          }
          return ucwords(strtolower($n));
      }
      
      $f = array_map('ucwords_array', $f);
      

      After this you can extract the data from uasort using uksort :

      $f['titulo'] = $_POST['titulo'];
      
      $f = array_map('ucwords_array', $f);
      extract($f);
      
      echo $titulo;
      
    • Use views in frameworks:

      An example of a framework that uses associative arrays is Laravel, but when you access the view variables are extracted, probably using usort , here is an example of a route:

      Route::get('/', 'UserController@home');
      

      UserController.php:

      class UserController extends Controller
      {
          public function home(Request $request)
          {
              $f = array();
      
              $f['titulo']   = $request->input('titulo');
              $f['conteudo'] = $request->input('conteudo');
              $f['data']     = $request->input('data');
      
              return view('greeting', $f);
          }
      }
      

      View:

      <html>
          <body>
              <h1>Titulo: <?php echo $name; ?></h1>
              <p>conteudo: <?php echo $conteudo; ?></p>
              <p>data: <?php echo $data; ?></p>
          </body>
      </html>
      

    Completing

    This will not always be useful and in most cases it may even be totally redundant. About the video, I do not really understand why he does this, maybe because he likes it that way, or because he's so used to it or just learned it this way.

    I'm not going to criticize because I do not know which video you're talking about I've even tried, but I did not find it. But I'll say something that goes for any programmer, even for who already has experience, there are many ways to be doing the same thing, until the beginning of this year I did some things in my codes in a way, but throughout the year I changed totally my habits. This is normal, sometimes we think it is the most practical or correct way, but over time we find new ways (and even manias).

    One thing I'm going to tell you is, do not believe everything they tell you, or follow exactly as they told you, I've heard a lot of things that sound wrong, see this question:

    I found up error in the php documentation:

    This is for any language, not just php.

        
    17.11.2015 / 19:18
    6

    Without the context, it is difficult to explain why it stores the variables in a single array. You may already be preparing to pass the variables as parameters for running the PDO, as the example below:

    $params = array();
    $params[':id'] = $_POST['id'];
    $params[':name'] = $_POST['name'];
    
    $sql = 'SELECT * FROM tabela WHERE id = ":id" AND name = ":name"';
    $res = $conn->prepare($sql);
    $res->execute($params);
    $list = $res->fetchAll();
    

    However,

    To retrieve global variable values always use the treatment functions . Using global variables directly is an unsuitable practice .

    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    

    Although the PDO already treats the values to prevent SQL Injection when used as in the example I gave it is very important that it validates the values received in these variables, so it will not risk leaving unknown unknowns.

    About how you create your variables, some say they improve readability, others judge it as bullshit, others see how to take up memory, but what matters is being aware of what you are doing.

        
    17.11.2015 / 17:53
    5

    Technically and in terms of both ways, there is no problem.

    What can define whether a technique, style or even a concept is more appropriate than another is the ultimate goal.

    Will the data be used for what purpose?

    From this point you decide which technique to use.

    The technique using an array to receive the array $_GET or $POST has the advantage that it can be simpler to manage. As an example, if you need to delete everything, just delete a single object.

    $f['titulo'] = $_POST['titulo'];
    $f['conteudo'] = $_POST['conteudo'];
    $f['data'] = $_POST['data'];
    
    /**
    Aqui faz os paranauê..
    */
    
    /**
    Após terminar tudo que tinha para fazer, podemos descartar simplesmente assim:
    */
     unset($f);
    
    
    /**
    No outro modo teria que fazer isso:
    */
    unset($titulo);
    unset($conteudo); 
    unset($data); 
    
    /**
    Uma forma resumida
    */
    unset($titulo, $conteudo, $data);
    

    * This is a simple example. Obviously if that was the only advantage, it would be ridiculous.

    After all, what's the best?

    There is no better way to do this. Whenever you think "which is the best," always think that there are N ways to solve something by reaching the same result. Instead of thinking "which is best", think "which one is right for this business model?".

    For any technique, think about where you want to go. What's the point. What outcome do you expect to achieve?

    Think of performance as well. What costs more to run? Is it worth using a more sophisticated feature that consumes more processes for something small and simple? Is it worth choosing a simple path because it is easier even if you have to modify it in the future for an implementation or create something robust and modular to simplify future implementations?

    Choices depend on planning, which is based on the business model.

    Let's see in practice a more sophisticated situation.

    Why not use the global variables $_POST and $_GET directly? Why consume memory by "cloning" the same data?

    In more sophisticated systems, we may want to keep the original data received for $_GET and $_POST , because at the moment of receipt, we need to validate, sanitize, and filter.

    A sanitization or filtering can modify the original data received. For a business model that wants to see the original data, it is not a good deal. So in this case it is more appropriate to "clone" the data to a new object where the data will be manipulated and the original data will remain intact.

    Delete redundancies

    A simple tip that prevents code repetition.

    Instead of receiving one by one

    $f['foo'] = $_POST['foo'];
    $f['bar'] = $_POST['bar'];
    

    Only receive the entire array

    $f = $_POST;
    

    If you want to create variables with index names, use variable variables in a loop of repetition

    foreach ($_POST as $k => $v)
        $$k = $v;
    
        
    18.11.2015 / 04:54
    2

    Good morning Marcos,

    What he is doing is storing the values obtained by post in an array, whose values are given a string key that identifies them, instead of a numeric key of type integer 1, 2, 3, and so on.

    Whether this is better or worse depends solely on what you want to do with those values later. If you need to iterate over this array with a loop for example.

        
    17.11.2015 / 14:33