Answer the question
In order to leave comments, you need to log in
Should I create additional variables for better readability of the code?
It is possible to write highly readable and self-documenting code, but sometimes this requires creating additional variables and breaking lines of code. How good or bad is this practice?
Simple example:
// $prices - двумерный массив с ценами
// $type - тип параметра
foreach($prices as $price) {
$amount = $price[$type];
$total += $amount;
}
// $prices - двумерный массив с ценами
// $type - тип параметра
foreach($prices as $price) {
$total += $price[$type];
}
Answer the question
In order to leave comments, you need to log in
Depends on the situation. In your example, the second one. But, in the case of the code below - the first one.
foreach($houses as $house) {
$current_floor = $house[$floor];
$rooms_count = count($current_floor['flats']['1-room']); // например, только 1-комнатные
$total_rooms += $rooms_count;
/* вышенаписанное гораздо лучше, чем
$total_rooms += count($house[$current_floor]['flats']['1-room']);
*/
}
I look at the following criteria to take out to a variable:
1) collection[key] is used more than once
2) key is too heavy (complicated) - then I take out the key (keeping the logic of point 1)
There are no universal rules here. Look at the code with a fresh eye and think, will the steps of the algorithm be obvious in a white view?
You can also rely on the proximity of the algorithm to natural language: "for each price tag, add a certain type of price tag to the total price tag." That is, the additional variable here rather adds verbosity - an extra entity that needs to be kept in mind.
2nd.
it is not only shorter, but also much less resource intensive.
Well, and ... "crowbar in the sleeve": php.net/manual/ru/function.array-sum.php
And it's easier like this:
$total = array_column($prices, $type);
$total = array_sum($total);
The most common problem...
I would choose the third way and call $type humanly, without creating an extra variable and explicitly making it clear that "type" is not some abstract substance, but a concrete thing, in this case the sum type.
<?php
foreach($prices as $price) {
$total += $price[$amountType];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question