Verify value in a PHP array and reasign result to the variable - php

I would be much grateful if you could help in solving this PHP issue.
I needs to verify the value of $fl_blackriver, $fl_flacq, etc...
if value=="", assign 0 to this value
update the corresponding variable with the updated value
$fl_blackriver = $_REQUEST['fl_blackriver'];
$fl_flacq = $_REQUEST['fl_flacq'];
$fl_grandport = $_REQUEST['fl_grandport'];
$fl_moka = $_REQUEST['fl_moka'];
$fl_pamplemousses = $_REQUEST['fl_pamplemousses'];
$fl_plaineswilhems = $_REQUEST['fl_plaineswilhems'];
$fl_portlouis = $_REQUEST['fl_portlouis'];
$fl_rivieredurempart = $_REQUEST['fl_rivieredurempart'];
$fl_savanne = $_REQUEST['fl_savanne'];
$fl_finalize = $_REQUEST['fl_finalize'];
$district = array($fl_blackriver,$fl_flacq,$fl_grandport,$fl_moka,$fl_pamplemousses,$fl_plaineswilhems,$fl_portlouis,$fl_rivieredurempart,$fl_savanne,$fl_finalize);
$arrlength = count($district);
for($x = 0; $x < $arrlength; $x++)
{
if ($district[$x]=="")
$district[$x] = "0";
}

This doesn't look nice but it should do the trick:
$fl_blackriver = $_REQUEST['fl_blackriver'];
$fl_flacq = $_REQUEST['fl_flacq'];
$fl_grandport = $_REQUEST['fl_grandport'];
$fl_moka = $_REQUEST['fl_moka'];
$fl_pamplemousses = $_REQUEST['fl_pamplemousses'];
$fl_plaineswilhems = $_REQUEST['fl_plaineswilhems'];
$fl_portlouis = $_REQUEST['fl_portlouis'];
$fl_rivieredurempart = $_REQUEST['fl_rivieredurempart'];
$fl_savanne = $_REQUEST['fl_savanne'];
$fl_finalize = $_REQUEST['fl_finalize'];
$district = array(
'fl_blackriver' => $fl_blackriver,
'fl_flacq' => $fl_flacq,
'fl_grandport' => $fl_grandport,
'fl_moka' => $fl_moka,
'fl_pamplemousses' => $fl_pamplemousses,
'fl_plaineswilhems' => $fl_plaineswilhems,
'fl_portlouis' => $fl_portlouis,
'fl_rivieredurempart' => $fl_rivieredurempart,
'fl_savanne' => $fl_savanne,
'fl_finalize' => $fl_finalize
);
foreach ($district as $key => $value) {
if ($value === "") {
$$key = "0";
}
}

You can do that using ternary operator like this,
$fl_blackriver = !empty($_REQUEST['fl_blackriver']) ? $_REQUEST['fl_blackriver'] : 0 ;
$fl_flacq = !empty($_REQUEST['fl_flacq']) ? $_REQUEST['fl_flacq'] : 0 ;
$fl_grandport = !empty($_REQUEST['fl_grandport']) ? $_REQUEST['fl_grandport'] : 0 ;
$fl_moka = !empty($_REQUEST['fl_moka']) ? $_REQUEST['fl_moka'] : 0 ;
$fl_pamplemousses = !empty($_REQUEST['fl_pamplemousses']) ? $_REQUEST['fl_pamplemousses'] : 0 ;
$fl_plaineswilhems = !empty($_REQUEST['fl_plaineswilhems']) ? $_REQUEST['fl_plaineswilhems'] : 0 ;
$fl_portlouis = !empty($_REQUEST['fl_portlouis']) ? $_REQUEST['fl_portlouis'] : 0 ;
$fl_rivieredurempart = !empty($_REQUEST['fl_rivieredurempart']) ? $_REQUEST['fl_rivieredurempart'] : 0 ;
$fl_savanne = !empty($_REQUEST['fl_savanne']) ? $_REQUEST['fl_savanne'] : 0 ;
$fl_finalize = !empty($_REQUEST['fl_finalize']) ? $_REQUEST['fl_finalize'] : 0 ;

You can try the following process. It will check the value whether it is empty or not. If the value is empty then it will set the value to 0. Otherwise it will take the requested value.
$fl_blackriver = (isset($_REQUEST['fl_blackriver'])) ? $_REQUEST['fl_blackriver'] : 0;
$fl_flacq = (isset($_REQUEST['fl_flacq'])) ? $_REQUEST['fl_flacq'] : 0;
$fl_grandport = (isset($_REQUEST['fl_grandport'])) ? $_REQUEST['fl_grandport'] : 0;
$fl_moka = (isset($_REQUEST['fl_moka'])) ? $_REQUEST['fl_moka'] : 0;
$fl_pamplemousses = (isset($_REQUEST['fl_pamplemousses'])) ? $_REQUEST['fl_pamplemousses'] : 0;
$fl_plaineswilhems = (isset($_REQUEST['fl_plaineswilhems'])) ? $_REQUEST['fl_plaineswilhems'] : 0;
$fl_portlouis = (isset($_REQUEST['fl_portlouis'])) ? $_REQUEST['fl_portlouis'] : 0;
$fl_rivieredurempart = (isset($_REQUEST['fl_rivieredurempart'])) ? $_REQUEST['fl_rivieredurempart'] : 0;
$fl_savanne = (isset($_REQUEST['fl_savanne'])) ? $_REQUEST['fl_savanne'] : 0;
$fl_finalize = (isset($_REQUEST['fl_finalize'])) ? $_REQUEST['fl_finalize'] : 0;
$district = array($fl_blackriver,$fl_flacq,$fl_grandport,$fl_moka,$fl_pamplemousses,$fl_plaineswilhems,$fl_portlouis,$fl_rivieredurempart,$fl_savanne,$fl_finalize);

foreach($_REQUEST as $key => $value) {
if (! is_numeric($value)) {
$_REQUEST[$key] = 0;
}}
extract($_REQUEST);

I would do that in a variadic function returning an array when multiple arguments are given or source of any type when only one argument is present.
function request(string ...$names)
{
foreach ($names as &$v)
$v = '' === ($v = $_REQUEST[$v] ?? 0) ? 0 : $v;
return 1 === count($names) ? $names[0] : $names;
}
[$fl_blackriver, $fl_flacq] = request('fl_blackriver', 'fl_flacq');
$fl_grandport = request('fl_grandport');
$district = request('fl_blackriver','fl_flacq','fl_grandport','fl_moka','fl_pamplemousses','fl_plaineswilhems','fl_portlouis','fl_rivieredurempart','fl_savanne','fl_finalize');
var_dump($fl_blackriver, $fl_flacq, $fl_grandport);
var_dump($district);
To get key/value pairs in an associative array:
function request_assoc(string ...$names) : array
{
$names = array_flip($names);
foreach ($names as $k => &$v)
$v = '' === ($v = $_REQUEST[$k] ?? 0) ? 0 : $v;
return $names;
}

Related

how to reduce number of variables PHP

My code checks and updates the number of apartments a building has with different bedrooms (1,2,3,4,studio) and calculates their avg min rent price and avg max rent price for particular type of room. How do I reduce the number of variables in this code so its easier to read and work with, if I can do it with arrays and foreach loop how can I use them in this code?
$room_one = $room_two = $room_three = $room_four = $room_studio = 0;
$rentmin_one = $rentmin_two = $rentmin_three = $rentmin_four = $rentmin_studio = 0;
$rentmax_one = $rentmax_two = $rentmax_three = $rentmax_four = $rentmax_studio = 0;
foreach ($nodes as $node) {
$field_bedrooms = "input field value";
$field_rentmin = "input field value";
$field_rentmax = "input field value";
foreach ($field_bedrooms as $field_bedroom) {
if (!is_null($field_bedroom) && !empty($field_bedroom)) {
$bedrooms_nid = $field_bedroom['target_id'];
$bedrooms_vocab = $this->load($bedrooms_nid);
$bedroom_value = $bedrooms_vocab->getName();
if ($bedroom_value == 1) {
$room_one++;
$rentmin_one = $rentmin_one + $field_rentmin;
$rentmax_one = $rentmax_one + $field_rentmax;
}
elseif ($bedroom_value == 2) {
$room_two++;
$rentmin_two = $rentmin_two + $field_rentmin;
$rentmax_two = $rentmax_two + $field_rentmax;
}
elseif ($bedroom_value == 3) {
$room_three++;
$rentmin_three = $rentmin_three + $field_rentmin;
$rentmax_three = $rentmax_three + $field_rentmax;
}
elseif ($bedroom_value == 4 || $bedroom_value == '4+') {
$room_four++;
$rentmin_four = $rentmin_four + $field_rentmin;
$rentmax_four = $rentmax_four + $field_rentmax;
}
elseif ($bedroom_value == 'Studio') {
$room_studio++;
$rentmin_studio = $rentmin_studio + $field_rentmin;
$rentmax_studio = $rentmax_studio + $field_rentmax;
}
}
}
}
$avg_minrent['one'] = !empty($rentmin_one) && !empty($room_one) ? $rentmin_one / $room_one : '';
$avg_maxrent['one'] = !empty($rentmax_one) && !empty($room_one) ? $rentmax_one / $room_one : '';
$avg_minrent['two'] = !empty($rentmin_two) && !empty($room_two) ? $rentmin_two / $room_two : '';
$avg_minrent['three'] = !empty($rentmin_three) && !empty($room_three) ? $rentmin_three / $room_three : '';
$avg_minrent['four'] = !empty($rentmin_four) && !empty($room_four) ? $rentmin_four / $room_four : '';
$avg_minrent['studio'] = !empty($rentmin_studio) && !empty($room_studio) ? $rentmin_studio / $room_studio : '';
$avg_maxrent['two'] = !empty($rentmax_two) && !empty($room_two) ? $rentmax_two / $room_two : '';
$avg_maxrent['three'] = !empty($rentmax_three) && !empty($room_three) ? $rentmax_three / $room_three : '';
$avg_maxrent['four'] = !empty($rentmax_four) && !empty($room_four) ? $rentmax_four / $room_four : '';
$avg_maxrent['studio'] = !empty($rentmax_studio) && !empty($room_studio) ? $rentmax_studio / $room_studio : '';
return [f
$avg_minrent,
$avg_maxrent,
];

PHP evaluating the content of an array

I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912

Increment based on another incrementing variable

I have this odd situation and I can't think of a solution for it.
I have a variable $cat_count = 1; and I use it inside a loop and then do $cat_count++ somewhere below where I've used it.
Then I have another alphabetical counter which works the following way:
I have $alpha_string = 'abcdefghijklmnopqrstuvwxyz'; and $alpha_counter = 0;. I use this the following way - $alpha = $alpha_string{$alpha_counter}. I want my alphabetical counter to start counting from a, whenever $cat_count gets incremented by one.
So for example we would have this:
$cat_count = 1
$alpha = a
$alpha = b
$cat_count = 2
$alpha = a
$alpha = b
What I get momentarily is this:
$cat_count = 1
$alpha = a
$alpha = b
$cat_count = 2
$alpha = c
$alpha = d
Ideas?
Thank you.
following my answer in comments..
$counter = 0;
$cat_count = 1;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
$rule_id = null;
$public_cats = array();
while ($row = $db->sql_fetchrow($result))
{
if ($rule_id != $row['rule_id'])
{
$group_ids = array_map('intval', explode(' ', $row['groups']));
$is_grouped = false;
// Check if user can see a specific category if he is not an admin or moderator
if (!$auth->acl_get('a_') && !$auth->acl_get('m_'))
{
$is_grouped = (group_memberships($group_ids, $user->data['user_id'], true)) ? true : false;
}
else
{
$is_grouped = true;
}
// Fill $public_cats with boolean values
if ($is_grouped !== false)
{
$public_cats[] = $is_grouped;
}
$rule_id = $row['rule_id'];
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
'CAN_SEE_CAT' => $is_grouped
));
$cat_count++;
$counter = 0;
}
$uid = $bitfield = $options = '';
generate_text_for_storage($row['rule_desc'], $uid, $bitfield, $options, $row['bbcode'], $row['links'], $row['smilies']);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($row['rule_desc'], $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter}
));
$counter++;
}

Any way to speed up this Magento code?

Is there any way to speed up this Magento code? Currently it is looking through about 2k products and takes approximately 20 minutes to run.
I'm guessing the issue is around the product->load() call, but I'm not familiar enough Magento to know the overhead it takes.
Thank you.
from controller
Mage::dispatchEvent(
'category_rule_save',
array(
'rule_id' => $id,
'attribute_code' => $data['attribute_code'],
'operator' => $data['operator'],
'value' => $data['value'],
'category_id' => $data['category'],
'store_id' => $data['store_id']
)
);
from Observer.php
public function onCategoryRuleSave($observe)
{
$collection =
Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect($observe['attribute_code']);
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
foreach ($collection as $product) {
$productId = $product->getId();
$product = $product->load($productId);
$productAttributeValue = '';
$productAttributeValue =
Mage::getModel('catalog/product')->load($productId)
->getAttributeText( $observe['attribute_code'] );
$r = 0;
if ( is_numeric($observe['value']) ) {
switch($observe['operator']) {
case "<":
$r = ($productAttributeValue < $observe['value']) ? 1 : 0;
break;
case ">":
$r = ($productAttributeValue > $observe['value']) ? 1 : 0;
break;
case "<=":
$r = ($productAttributeValue <= $observe['value']) ? 1 : 0;
break;
case ">=":
$r = ($productAttributeValue >= $observe['value']) ? 1 : 0;
break;
case "==":
$r = ($productAttributeValue == $observe['value']) ? 1 : 0;
break;
case "!=":
$r = ($productAttributeValue != $observe['value']) ? 1 : 0;
break;
}
}
else {
switch($observe['operator']) {
case "==":
$r = (
strcmp(strtolower($productAttributeValue) , strtolower($observe['value'])) == 0
) ? 1 : 0;
break;
case "!=":
$r = (
strtolower($productAttributeValue) != strtolower($observe['value'])
) ? 1 : 0;
break;
}
}
if ($r==1) {
$write->query(
"REPLACE INTO `catalog_category_product` (`category_id`, `product_id`)
VALUES (" . $observe['category_id'] . "," . $product->getId() . ")"
);
}
}
}
Try replacing the product loading with:
...
foreach ($collection as $product) {
$productAttributeValue = $product->getAttributeText( $observe['attribute_code'] );
$r = 0;
...
You're loading a product object 2 extra times. The $product variable in the foreach already is the loaded product with the attribute that you need to work with. Loading a $product object with all of its attributes is expensive given Magento's EAV database structure.
1.$collection =
Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect($observe['attribute_code']);
2.Mage::getModel('catalog/product')->load($productId)
->getAttributeText( $observe['attribute_code'] );
3.$product = $product->load($productId);
That is really awful :)
$collection =
Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*');//this string should load all of the product attributes
There also were some methods to add product websites, product store and some others.

Create a 20px left padding when this function loops

How can I format this code block so that every time this loop happens,
it moves each hyperlink element 20px from the left?
It's working at the moment but for the whole div not single items.
Example:
- LINK 1
-- LINK 2
--- LINK 3
Any help would be appreciated!
$linkArray = array();
$thisDir = '';
$baseDir = ($htmlRoot == '') ? '' : $htmlRoot;
for ($n=0; $n<count($dirArray); $n++) {
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:20px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
$results = (count($linkArray) > 0) ? implode($separator, $linkArray) : '';
Well hmmm. You are already counting your iterations with the $n variable. SO:
EG.
for ($n=0; $n<count($dirArray); $n++) {
$pxvar = $n * 20;
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:'.$pxvar.'px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
Note: the first iteration will have a padding of 0px. Not sure if thats how you want it?

Categories