How to write variables in PHP?

Asked

Viewed 811 times

11

I was watching the videos of Robson V.Leite and I realized that at a given moment he retrieves information from the forms to enter into the database in a different way than I use, the only way I knew until then. It stores variables in index form. Ex:

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

Why would he store the variables this way and not the way I’ve always used them? I do so:

$titulo = $_POST['titulo'];
$conteudo = $_POST['conteudo'];
$data = $_POST['data'];
  • 1

    You can’t say anything in this context. Assigning a key array to another is pretty cool...

  • @rray did not understand his phrase. Why is cool?

  • Why doesn’t it make sense for you to copy an item-by-item array, for what purpose? why not use $_POST straight? what else is done with $f?

  • Where did you get that reference ?

  • If you are creating new variables just to store the data of another variable, in most cases it would just be memory waste. Use the original variable.

  • 2

    For God’s sake! Don’t give answers teaching to use extract directly in $_POST, otherwise you will create a programmer who creates unsafe code !

  • 1

    Today, even learning is a risk. There are still many other practices that are not recommended in the answers.

  • 1

    @Any Marcosvinicius helped you more? You need something to be improved?

Show 3 more comments

7 answers

19

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

I, for example, don’t usually do either of the two things (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 so, without question. Some rare cases believe it is best to do so. It may be better if you are going to use the externally coming variable multiple times. But the improvement is essentially to write something simpler.

Actually I "don’t understand" why people love creating variables where they’re not needed. This happens everywhere, someone did wrong or for a very specific reason, then the other "programmers" copy without trying to understand why they do it. There must be a reason to create variable. In general this reason is that you really need to store a specific value that will be used several times. I even understand that it can give more readability, but if you will use only once, you will not do any operation, the $_POST is of good size.

In the case of his code, it’s also simpler, but it’s so little that I think it’s best not to. Either do it the second way or leave the pattern.

Of course, his code may be like this for some other reason we don’t know, but I’m not going to speculate on this like other answers, after all it’s just speculation.

The fact is that:

  1. There is no reason to do this in the context presented
  2. 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 intention we cannot say that it would use as a PDO parameter because the syntax is different. If you’re gonna have to change the syntax later then why don’t you let it change everything?

And if you’re going to use it in some function that awaits a array, why not use your own $_POST? Why create another?

Of course, processing external data is important in most cases, but the example is not doing this. And it will be done at the time of taking the data from $_POST is that the check/sanitization should be done and then probably play on local variables. Even if play on another array associative, not yet shown.

  • TL;DR : "Understand the context, then create auxiliary variables"?

  • 7

    I think not, it would be more a "1. Understand the context. 2. Do not create auxiliary variables where you do not need". But to be sure you have to know the context :P

  • The context is irrelevant in this case because it is an introduction course to the CRUD and database. I think it will in the future use this to treat as array to do something. Variables are often irrelevant, of course

  • 5

    Context is always relevant, even if it is a "course". And precisely because it is a "course", it should not teach to do wrong. Unless the rest of the code shows you have a reason to perform this operation. This is context. If it’s the way I’m thinking (I can only guess without seeing the context) I shouldn’t use any of this, neither the first nor the second form. If it is otherwise, the second form is not all bad. If it will use in the future, it lacks context and didactic lack for it. Variables are not irrelevant. If any are in this situation, it should be removed.

  • @bigown In this case I believe that your response induces to leave in the code a major security flaw. In PHP do not treat global variables as $_POST and $_GET is too risky, even more to handle database.

  • 1

    @marcusagm on the contrary. If you treat them, you will be using them only once, and the result of the treatment is that it will be used from then on. That’s why I talk about the context.

  • @bigown what I mean is that there are native functions to recover these values, and abandon the direct use of these global variables.

  • 1

    @marcusagm first, that’s exactly what I said. But if you’re going to talk about these functions, it’s another matter. Here you ask about the use of variables. What will be done with them is off-topic in this question. If you look at security, the two ways are potentially wrong. But they may not be, because wanting to treat anything without knowing why you’re doing it, is also wrong.

Show 3 more comments

12

In addition to the @Maniero response, it really is 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 to be able to "simplify" the use of the variable. But this really isn’t necessary.

As you demonstrated in the example:

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

It would be easier to do so:

$f = $_POST;

But that would not give any advantage, because 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 more useful if there were some treatment in their values.

Example:

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

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

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

Another very common case of using variables to "copy values" is in return of functions. Because instead of having to process it all over again, it’s 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;
}

Then we could do:

 $cidade = get_nome_cidade(10);

 $banco->salva(['cidade' => $cidade]);

 echo "Ele salvou a cidade {$cidade}";

Because then, since the value of the function would always be the same, but the cost of obtaining it being high, we could worry about saving it in a variable.

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

'Cause you better do it:

 $nome = $_POST['usuario']['nome_completo_usuario']

 echo "O nome do usuário é {$nome}":

Than to do this

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 will forget the names, so big they are!

And, to complement, there is nothing wrong between your way of doing and his way. It is only unnecessary, in my opinion.

10

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

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

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

The probable reasons are:

  • Use php native functions

    If you use associative arrays, you can use several 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, sizeof, sort, uasort, uksort and usort

    A good example is the array_map, with it is possible to access all variables do something with them, for example search all values that are possibly words and apply ucwords (is 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 $f using extract():

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

    An example framework that uses associative arrays is Laravel, but when accessing view variables are extracted, probably using the extract(), here an example of 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>
    

Concluding

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

I’m not gonna criticize you because I don’t know what video you’re talking about, but I couldn’t find it. But I’ll tell you something that goes for any programmer, even for who already has experience, there are many ways to be do the same thing, until the beginning of this year I did some things in my codes in a way, but throughout the year I totally changed 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’ll tell you, don’t believe everything you’re told, or follow exactly as you’ve been told, I’ve heard a lot of wrong that sounded right, look at this doubt:

I even found error in php documentation:

This is for any language, not just php.

  • 1

    How cool huh!!!! I liked this answer. In the sense of keeping the variables within the $f which is the array enabling this array to be worked by all of the above functions and even extracted in the form of indices, variables ...

  • @Marcosvinicius edited and put an example of Laravel, I’m glad that the answer seems useful :) Thanks!

  • 1

    @Guilhermenascimento, No Laravel you don’t usually use the variable $_POST, but the method Input::get. I imagine you must have done it by example. Another thing is that if it is necessary to pass the data to view, it is not necessary to reassign the variable. Just pass it directly view('minha_view', $_POST). What many people confuse is that $_POST, despite being a superglobal, it is a common array, and can be removed with unset as any other variable (and for me should not be treated in a special way, to the point of having to reassign).

  • 2

    In the example of array_map, you don’t need to reassign the value either! You could create directly $f = array_map('funcao', $_POST). Unless you want to work with some data from $_POST and others not. In this case, no laravel you can use $f = Input::only('texto', 'conteudo', 'data'). Already in pure PHP, you would have to reassign. That is, if AP is picking up some data from $_POST, and not all, this is useful. If not, this is useless.

  • 2

    Actually I wasn’t explaining about the $_POST, was something more vector-oriented, maybe I used as an example the author’s code in a place that can confuse. @Wallacemaxters but really your tip is totally valid +1

  • @Wallacemaxters yes I am aware about the Standard and how the layers work, however as I said maybe the example was not the best, my focus really was to explain when it will be necessary to use an array. Maybe I’ll edit it later.

  • I’m not saying the answer was bad, @Guilhermenascimento, it was just a comment ;)

  • 2

    @Wallacemaxters I know :P and so I positive, understand that all constructive criticism is positive and that’s what you did, I just agreed with you saying I didn’t really choose the best example.

Show 3 more comments

6

Without context it is difficult to explain why it stores variables in a single array. Maybe you are already preparing to pass the variables as parameters for PDO execution, 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();

But receive various ways $_POST and $_GET directly is a risk, because these variables can be manipulated by the user, leaving gaps for SQL Injection for example.

To recover values from global variables always use the treatment functions. Use global variables directly is not a recommended practice.

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

Although PDO already treat the values to make SQL Injection impossible when used as in the example I gave it is very important to validate the values received in these variables, so you will not run the risk of leaving unknown faults.

About how each one creates their variables, some say they improve readability, others judge as bullshit, others see how to occupy memory at all, but what matters is to be aware of what you’re doing.

  • 1

    Although the answer is not focusing on what you were asking, I agree with this. The problem is that the link indicated tells to do something always, as if it were a single rule. And it is not so true. As you said you have to know what you are doing. To follow the rule because someone said that you cannot. But I do not want to continue in this matter, because besides being off-topic, will provoke debate.

  • It’s not out of context, I actually tried to show an application example for the first case and not judge what he did. As the question does not contextualize becomes difficult to define, the part of the treatment and security is a bonus, and I agree with you some cases use these functions is not convenient, however it is not the majority of cases. Just to conclude the matter.

  • No need for double quotes: 'SELECT * FROM tabela WHERE id = :id AND name = :name';

5

Technically and practically, in both forms, no problem.

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

The data will be used for what purpose?

From this point it is decided 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);

*That is a mere example. Obviously if that were the only advantage, it would be ridiculous.

After all, which the best?

There is, in this case, the best. Whenever you think "which is best," always think that there are N ways to solve something by achieving the same result. Instead of thinking "what’s best," think "what’s best for this business model?".

For any technique, think about where you want to go. What is the goal. What is the result you expect to get.

Also think about the performance. What costs more to be executed? Is it worth using a more sophisticated resource that consumes more processes for something small and simple? It’s worth choosing a simple path because it’s 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 global variables directly $_POST and $_GET? Why consume memory by "cloning" the same data?

In more sophisticated systems, we may want to keep the original data received by $_GET and $_POST, because at the time of receipt, we need to make validations, sanitizations and filtrations.

A sanitization or filtration can modify the original data received. For a business model that wants to see the original data, it is not good business. Therefore, in that 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.

Eliminate redundancies

A simple tip that avoids code repetition.

Instead of getting one by one

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

Just take the entire array

$f = $_POST;

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

foreach ($_POST as $k => $v)
    $$k = $v;
  • 2

    Daniel, this last example of foreach is totally insecure. You can enable the client to change the variable of your system, since you are setting the variables dynamically. Think: If I have a variable called $usuario and the guy maliciously create a form (via console or more advanced with Postman) he may change the content of his variable. That’s why register_globals was removed from PHP due to this insecurity

  • 1

    yes Wallace. It was merely an example, because before allowing to create variables in this way, one must have a control of the names of the parameters allowed for this. If we were to discuss all the details and their ramifications, it would make the answer very complicated and broad. For such basic details, the programmer is expected to be aware, given that the focus here is not specifically on security

  • You also don’t need to be too eager to teach everything so thoroughly. A beginner programmer, inexperienced, cannot assimilate everything that an experienced one teaches, especially if it is something very extensive and complex. Think of it as talking to a child or a baby. When a child asks about what a computer is, for example, you will not teach a class on the history of computers, electronics, programming logic, engineering, etc.. You’ll say it’s a kind of TV to open youtube and watch Pepa Pig.. Get it?

2

Good morning Marcos,

What he is doing is storing the values obtained by post in an array, whose values receive a string key that identifies them, rather than 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 these values later. If you need to iterate over this array with a loop for example.

0

You just didn’t know how to separate the wheat from the chaff.

This is not a variable, this is an array $f, with a key "title":

$f['titulo'] = 'título';

That is a variable:

$titulo = 'título';

Variables were invented to store a certain value and load it through methods, conditions, etc...

The array is used to map a collection, or load a higher amount of data.

You can use both, it will depend on your need, the difference is that using in the form of array, you will have a greater elasticity, but will store more memory for it.

Browser other questions tagged

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