I have many elseif statements. How can i optimize them? - php

Is there any way to optimize this code? I mean its working and all but it seems with lots of "elseif" its actually not so optimized:
foreach ($plenty_variation['properties'] as $row) {
if (strpos($row['relationValues']['0']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['0']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
elseif (strpos($row['relationValues']['1']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['1']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
elseif (strpos($row['relationValues']['2']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['2']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
}
In $row['relationValues']['0']['value'] the ['0'] is inconsistent and not always the same.

Why don't you use another loop?
foreach ($plenty_variation['properties'] as $row) {
for($i = 0; $i < count($row); $i++){
$value = $row['relationValues'][$i]['value'];
if(strpos($value, $needle_de_0) === 0){
$shopware["translations"][$i]["customFields"]["free" . $i] = str_replace("Text_de_0_", "", $value);
break;
}
}
}
In the case above I take that you'd like to loop the $shopware['translations'] positions as the same of the $plenty_variation['properties']. If this is not the case, just let it fixed:
$shopware["translations"]["0"]["customFields"]["free1"]

Related

Variable variables counted php

I know the title isn't that good, BUT I really don't know how to describe it in one setence and I need help.
Currently I have this type of disastrous code that count every $type of product there is in the DB (I have 20-30 types, not 2 only):
$cong = 0;
$refr = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
if ($arr[$t]['product_type'] == 'Congélateur') {
$cong += 1;
}
if ($arr[$t]['product_type'] == 'Réfrigérateur') {
$refr += 1;
}
$t++;
}
}
And I do stuff with it after. But I was disgusted to see that code, so I tried to minimize it, but I can't figure it out, I tried that:
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 1;
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n++;
}
}
$t++;
}
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>
Output:
cong=9
refr=1
What we should expect regarding the DB (In the database, there's 2 cong and 6 refr):
cong=2
refr=6
Any sugestion? Thank you!
You're really making this more complicated than it needs to be. Variable variables are almost never the solution and can always be replaced with an array.
The code you're working with makes no sense, why is it assigning $row to another array and then using a counter to access it? The answer you accepted includes 4 loops, one of them nested.
if (mysqli_num_rows($result) === 0) {
// always exit early rather than indent yourself to death
return false;
}
while ($row = mysqli_fetch_assoc($result)) {
$type = $row["product_type"];
$counts[$type] = ($counts[$type] ?? 0) + 1;
}
print_r($counts);
Demo: https://3v4l.org/8cuis#focus=7.3.28
Counters (which count the type names in your example) should be initialised to 0 not to 1.
You also need to increment $$type_n2 in DB read loop. I'd avoid variable variables if possible.
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 0;
}
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n2++; // not $$type_n
}
}
$t++;
}
foreach ($type as $type_n => $type_m) {
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>

Auto Description From Tags

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

Value not saving outside foreach loop

I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam

Foreach in function

I got a question that hopefully is easy to answer.
In the function below the part "foreach($daten as $row)" is ignored in the second turn. Can somebody tell me, why the function acts that way?
I already tried to delete the "break"... no success.
function verweis_show($string,$art,$daten){
$ausgang = preg_split("/\[-\[(.*?)\/(.*?)\/(.*?)\]-\]/", $string,0,PREG_SPLIT_DELIM_CAPTURE);
$n = 0;
foreach($ausgang as $teil)
{
$n++;
if($n == 1)
{
$ergebnis .= $teil;
}
elseif($n == 2)
{
$stat_id = $teil;
}
elseif($n == 3)
{
$rel_id = $teil;
if ($art != "old")
{
$z = 0;
// wird im zweiten durchlauf seltsamerweise nicht noch einmal durchlaufen
foreach($daten as $row)
{
$z++;
if ($row['id'] == $stat_id)
{
$rel_id = $z;
break;
}
}
}
}
elseif($n == 4)
{
$ergebnis .= "<div contenteditable='false' id='text_$stat_id' class='$teil' tabindex='-1'>$rel_id</div>";
$n = 0;
}
}
return $ergebnis;
}
Foreach requires that it either has an array, or an object that has the traversable interface implemented, which PDOStatement probably does not.

Storing array in a variable

I'm trying to replace the code below
$Palette = array(
"0"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"1"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"2"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"3"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"4"=>array("R"=>176,"G"=>46,"B"=>224,"Alpha"=>100),
);
with something similar but different values for the R, G and B. I have written the code below so far as a replacement:
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$colour[$x] = '"'.$x.'"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),';
}
else
{
$colour[$x] = '"'.$x.'"=>array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100),';
}
$x++;
}
while ($x <= '4');
$allcolours = $colour[0].$colour[1].$colour[2].$colour[3].$colour[4];
however, when I implement it into my script using the line below , it doesn't work.
$Palette = array($allcolours);
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$Pallete[$x] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Pallete[$x] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
$x++;
}
while ($x <= '4');
there is a little excessive usage of $x.
as a matter of fact, you don't need that variable at all
$Palette = array();
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
foreach ($incrementarray as $value)
{
if ($correct == $value)
{
$Palette[] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Palette[] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
}
you need to create array, not the PHP code to create array.

Categories