Shorter code with For - php

Is there any way to make this code shorter ?
If ($Item_1 != "_") { $items1 = explode("_", $Item_1); } Else {}
If ($Item_2 != "_") { $items2 = explode("_", $Item_2); } Else {}
If ($Item_3 != "_") { $items3 = explode("_", $Item_3); } Else {}
If ($Item_4 != "_") { $items4 = explode("_", $Item_4); } Else {}
If ($Item_5 != "_") { $items5 = explode("_", $Item_5); } Else {}
If ($Item_6 != "_") { $items6 = explode("_", $Item_6); } Else {}
If ($Item_7 != "_") { $items7 = explode("_", $Item_7); } Else {}
If ($Item_8 != "_") { $items8 = explode("_", $Item_8); } Else {}
If ($Item_9 != "_") { $items9 = explode("_", $Item_9); } Else {}
If ($Item_10 != "_") { $items10 = explode("_", $Item_10); } Else {}
If ($Item_11 != "_") { $items11 = explode("_", $Item_11); } Else {}
If ($Item_12 != "_") { $items12 = explode("_", $Item_12); } Else {}
I try it make shorter with For but it doesnt work example:
For ($i = 1; $i <= 12; $i++) {
If (${$Item_ . $i} != "_") .... dont work for me :/
}
Any ideas?

The idea is good. You just had a little error while building the variable name. Use the following code:
for ($i = 1; $i <= 12; $i++) {
if (${"Item_$i"} != "_") .... should work
}
What you are doing is called variable variables in php. Check the manual about that for further info and examples.
Another idea: Why not using an array? this should suite better here:
$item = array (
'foo', 'bar', 'test', 'xyz', ...
);
for ($i = 1; $i <= count($item); $i++) {
if ($item[$i] != "_")
}
Further note, that you can use the ternary operator to shorten the if statement. (note that I wouldn't do that in this situation because it is less readable, but I'll at least mention it for completeness):
$item[$i] != "_" ? $other[$i] = 'something' : 1; // no else block, just a `NOP 1`;

For clarity try this:
$item_var = "Item_".$i;
If ($$item_var != "_"){}

You should probably be using arrays instead if var1, var2, etc. You could easily use a loop too.

Related

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

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"]

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.

PHP recursive function nesting level reached

Good day. I have a parcer function that taker an array of string like this:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']
And recursivelly elevates a level those starting with asterix to get this
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']
And the function is:
function recursive_array_parser($ARRAY) {
do {
$i = 0;
$s = null;
$e = null;
$err = false;
foreach ($ARRAY as $item) {
if (!is_array($item)) { //if element is not array
$item = trim($item);
if ($item[0] === '*' && $s == null && $e == null) { //we get it's start and end if it has asterix
$s = $i;
$e = $i;
} elseif ($item[0] === '*' && $e != null)
$e = $i;
elseif (!isset($ARRAY[$i + 1]) || $s != null && $e != null) { //if there are no elements or asterix element ended we elevate it
$e = $e == NULL ? $i : $e;
$head = array_slice($ARRAY, 0, $s);
$_x = [];
$inner = array_slice($ARRAY, $s, $e - $s + 1);
foreach ($inner as $_i)
$_x[] = substr($_i, 1);
$inner = [$_x];
$tail = array_slice($ARRAY, $e + 1, 999) or [];
$X = array_merge($head, $inner);
$ARRAY = array_merge($X, $tail);
$s = null;
$e = null;
$err = true;
}
} else {
$ARRAY[$i] = recursive_array_parser($ARRAY[$i]); //if the item is array of items we recur.
}
$i++;
if ($err == true) {
break 1;
}
}
} while ($err);
return $ARRAY;
}
When this function runs, i get "Fatal error: Maximum function nesting level of '200' reached, aborting!" error.
I know it has something to do with infinite recursion, but i can't track the particular place where it occurs, and this is strange.
I don't normally rewrite code, but your code can be reduced and simplified while, from what I can see, getting the desired result. See if this works for you:
$a = array('a','b','c','*d','*e','**f','g','*h');
print_r($a);
$a = recursive_array_parser($a);
print_r($a);
function recursive_array_parser($array)
{
$ret = array();
for($i=0; $i<sizeof($array); $i++)
{
if($array[$i]{0}!='*') $ret[] = $array[$i];
else
{
$tmp = array();
for($j=$i; $j<sizeof($array) && $array[$j]{0}=='*'; $j++)
{
$tmp[] = substr($array[$j],1);
}
$ret[] = recursive_array_parser($tmp);
$i = $j-1;
}
}
return $ret;
}
Note that it isn't possible for $array[$i] to be an array, so that check is removed. The recursion takes place on the temp array created when a * is found. The $i is closer tied to $array to reset it properly after parsing the series of * elements.
Here's my solution. No nested loops.
function recursive_array_parser($arr) {
$out = array();
$sub = null;
foreach($arr as $item) {
if($item[0] == '*') { // We've hit a special item!
if(!is_array($sub)) { // We're not currently accumulating a sub-array, let's make one!
$sub = array();
}
$sub[] = substr($item, 1); // Add it to the sub-array without the '*'
} else {
if(is_array($sub)) {
// Whoops, we have an active subarray, but this thing didn't start with '*'. End that sub-array
$out[] = recursive_array_parser($sub);
$sub = null;
}
// Take the item
$out[] = $item;
}
}
if(is_array($sub)) { // We ended in an active sub-array. Add it.
$out[] = recursive_array_parser($sub);
$sub = null;
}
return $out;
}

Variable variables created within a for loop

I'd like to change this:
if ($week_day == "1")
{
$day1_hours = $value;
}
if ($week_day == "2")
{
$day2_hours = $value;
}
if ($week_day == "3")
{
$day3_hours = $value;
}
if ($week_day == "4")
{
$day4_hours = $value;
}
if ($week_day == "5")
{
$day5_hours = $value;
}
if ($week_day == "6")
{
$day6_hours = $value;
}
if ($week_day == "7")
{
$day7_hours = $value;
}
}
Into something more readable, like a for loop, or whatever other suggestions you all may have.
I tried to do:
for ($c=1; $c<8, $c++)
{
if ($week_day == $c)
{
$day".$c."_hours = $value;
}
}
But I know that is nowhere near correct, and I have no idea how to insert another variable within a variable.
Any help is appreciated!
Try this syntax.
${'day'.$c.'_hours'} = $value;
Try this
$hours[$week_day] = $value
Something like this
$week_day = 3;
$value = "hi";
${"day" . $week_day . "_hours"} = $value;
echo $day3_hours;
My interpretation.
$week = 7;
$day = array();
for($i=1; $i<=7; $i++){
$day[$i]['hours'] = $value;
}
You can declare the numbers of weeks you want and to pull the data you can do something like this:
echo $day[1]['hours']

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