check and display multiple values in for loop - php

I have for loop in which I have to check that the array that I am retriving should not empty. And if empty then don't display that field.
$checkboxes = array();
$text = array();
$Enhanced = array();
$Search = array();
$Landing = array();
$spotlights="";
for ($i = 1; $i <= 20; $i++) {
$checkboxes[$i] = $_POST[$i];
$text[$i] = $_POST[$i.'t'];
}
for ($p = 1; $p <= 20; $p++) {
$checkboxes[$p] = $_POST[$p];
$Enhanced[$p] = $_POST['Enhanced'.$p];
}
for ($q = 1; $q <= 20; $q++) {
$checkboxes[$q] = $_POST[$q];
$Search[$q] = $_POST['Search'.$q];
}
for ($r = 1; $r <= 20; $r++) {
$checkboxes[$r] = $_POST[$r];
$Landing[$r] = $_POST['Landing'.$r];
}
for ($j = 1; $j <= 20; $j++) {
if($checkboxes[$j]!="")
{
$spotlights=$spotlights."<strong>".$checkboxes[$j]."</strong><br>".$Enhanced[$j]."<br>".$Search[$j]."<br>".$Landing[$j]."<br>".$text[$j]."<br><br>";
}
}
echo $spotlights;
In above code, $Enhanced[$j], $Search[$j], $Landing[$j] may or may not be empty as these are checkboxes. If any of them is empty i don't want to print that. In above case if any of three field empty then it display <br/> which i don't want.
If I check them one by one or combination of them then my code will be longer.
How do I check in smarter way? How should I write the line of $spotlights=... so that it will display only non empty variables($Enhanced[$j], $Search[$j], $Landing[$j])?
I have tried bolow which is not working.
using functions:
for ($j = 1; $j <= 20; $j++) {
if($checkboxes[$j]!="")
{
$spotlights=$spotlights."<strong>".$checkboxes[$j]."</strong>".enhanced($j).search($j).landing($j)."<br>".$text[$j]."<br><br>";
}
}
function enhanced($j) {
if($Enhanced[$j]!="")
{
return "<br/>".$Enhanced[$j];
}
}
function search($j) {
if($Search[$j]!="")
{
return "<br/>".$Search[$j];
}
}
function landing($j) {
if($Landing[$j]!="")
{
return "<br/>".$Landing[$j];
}
}
above code not displaying values of $Enhanced[$j], $Search[$j], $Landing[$j]
checking values independently
for ($j = 1; $j <= 20; $j++) {
if($checkboxes[$j]!="")
{
$spotlights .= $spotlights."<strong>".$checkboxes[$j]."</strong>";
if($Enhanced[$j]!="")
{
$spotlights .= "<br>".$Enhanced[$j];
}
if($Search[$j]!="")
{
$spotlights .= "<br>".$Search[$j];
}
if($Landing[$j]!="")
{
$spotlights .= "<br>".$Landing[$j];
}
$spotlights .= "<br>".$text[$j]."<br><br>";
}
values are getting repeated by using above code.

Use array_filter.
Something like that:
$checkboxes = array_filter($checkboxes);
foreach($checkboxes as $checkbox)
{
$j = array_search($checkbox, $checkboxes)
$spotlights=$spotlights."<strong>".$checkboxes[$j]."</strong><br>".$Enhanced[$j]."<br>".$Search[$j]."<br>".$Landing[$j]."<br>".$text[$j]."<br><br>";
echo $spotlights;
}
array_filter will remove all NULL, false or '' from array, but will keep the position, so if you have in checkbox[3] something different, in checkboxes after array_filter will be on position 3. doesn't matter if on position 2 was NULL.

I don't think checking them individually will be a lot of trouble, as there are only three of them, but if you want to keep it one line, the line where you define $spotlights with this:
$spotlights=$spotlights."<strong>".$checkboxes[$j]."</strong>"
.($Enhanced[$j] != "" ? "<br>".$Enhanced[$j] : "")
.($Search[$j] != "" ? "<br>".$Search[$j] : "")
.($Landing[$j] != "" ? "<br>".$Landing[$j] : "")
."<br>".$text[$j]."<br><br>";
Hope this helped.

Related

form two arrays in a for loop checking for ignition state change condition

I need a logic which checks for ignition state change and if the ignition is on push that index into start array and if state then changes to off push into stop array so that I can consider one start array index to stop array index as one trip. I had a logic but this pushes all the start values and all the stop values I only need state change index
$isIgniOn = false; $startArray = array(); $stopArray = array();
for ($i = 0; $i < count($reportData); $i++) {
if ($reportData[$i]['ignition_status'] == 1) {
$startArray[] = $i;
$isIgniOn = true;
} else {
if ($isIgniOn) {
$isIgniOn = false;
$stopArray[] = $i;
} else {
$startArray[] = $i;
}
}
}
The problem is, you are not actually checking to see if the state has changed and need to add some extra logic in your program:
$isIgniOn = false; $startArray = array(); $stopArray = array();
for ($i = 0; $i < count($reportData); $i++) {
if ($reportData[$i]['ignition_status'] == 1 && !$isIgniOn) {
$startArray[] = $i;
$isIgniOn = true;
} elseif ($reportData[$i]['ignition_status'] == 0 && $isIgniOn) {
{
$isIgniOn = false;
$stopArray[] = $i;
}
}
}

php merging or concatenation strings when assigning a variable

PHP NOOB, i have been working on this code all day, but cant find any good way to fix it.
here is my code:
$priv = explode(',', '0,1,1');
$m = 'me';
for($i = 0; $i <= 2; $i++)
{
if($priv[$i] == '0')
{
$m.$i = 20;
}
else
{
$m.$i = 10;
}
}
Am trying to join $m.$i together and set it to 20 or 10, but i end up having me20 or me10 instead of me1 = 20 or me1 = 10 when i echo $m.$i which is legit, is there anyways to make this work?
$m.$i = 20;
This will assign $i = 20 and then concatenate it with $m and hence you will see me20.
What you need is $m . $i .= 20; instead. which will concatenate them altogether.
Fixed:
<?php
$priv = explode(',', '0,1,1');
$m = 'me';
for($i = 0; $i <= 2; $i++)
{
if($priv[$i] == '0')
{
echo $m . $i .= 20;
}
else
{
echo $m.$i .= 10;
}
}
?>
EDIT:
The above answer was a total misunderstanding, I realised you intended to create the variables:
for($i = 0; $i <= 2; $i++)
{
if($priv[$i] == '0')
{
${$m.$i} = 20;
echo $me0;
}
else
{
${$m.$i} = 10;
}
}
Assign it like so.
${$m.$i} = 20;
You are trying to dynamically create variables, so you have to do something like this:
$priv = explode(',', '0,1,1');
$m = 'me';
for($i = 0; $i <= 2; $i++)
{
if($priv[$i] == '0')
{
${$m.$i} = 20;
}
else
{
${$m.$i} = 10;
}
}
then try to priny $me0, $me1

Best way to use multiple nested loops

I am using php for this, but answers that are not language specific are also welcome.
I have several arrays of objects that I want to loop through and output in order. Each of the arrays have a different kind of object in them, but all of the objects have a unique order attribute.
For example:
$people = [{'name':'George','email':'George#test.com','order':'2'},{'name...];
$sandwiches = [{'type':'bacon','rating':'8/10','order':'1'},{'type...];
$restaurants = ....
$chefs = ...
...
What is the most efficient way to loop through them in order?
Assuming I can determine the maximum order I figured I could do something like:
for($i=0; $i< $maximumOrder; $i++)
{
for($j=0; $j< count($people); $j++)
{
if($people[$j]->order == $i)
{
//Do the things I want to do
break;
}
}
for($j=0; $j< count($sandwiches); $j++)
{
if($sandwiches[$j]->order == $i)
{
//Do the things I want to do
break;
}
}
for($j=0; $j< count($restaurants); $j++)
{
.....
}
But this isn't very good because even if the item with the desired order is found in people it will still continue looping through all the other arrays. I could just add a Boolean variable to show if the desired item has already been found (see below), but I am sure there are better ways to do this.
for($i=0; $i< $maximumOrder; $i++)
{
$found = false;
for($j=0; $j< count($people); $j++)
{
if($people[$j]->order == $i)
{
//Do the things I want to do
$found = true;
break;
}
}
if(!$found == true)
{
for($j=0; $j< count($sandwiches); $j++)
{
if($sandwiches[$j]->order == $i)
{
//Do the things I want to do
$found = true;
break;
}
}
}
if(!$found == true)
{
for($j=0; $j< count($restaurants); $j++)
{
.....
}
The below is based on #Victory's answer, with the addition of an elseif statement, to stop the while loop if it goes passed the desired order number (given these are now sorted arrays). This I believe should increase efficiency (at least with big arrays), but please correct me if I am wrong?
function orderArrayByOrder($a,$b)
{
return ($a->order < $b->order) ? -1 : 1;
}
$a1 = usort($people, "orderArrayByOrder");
$a2 = usort($sandwiches, "orderArrayByOrder");
$a3 = usort($restaurants, "orderArrayByOrder");
$c1 = count($a1)
$c2 = count($c2)
$c3 = count($c3)
$i1 = 0
$i2 = 0
$i3 = 0
// itertor over order
for ($curOrder ... $maxorder)
{
while ($i1 < $c1)
{
if($a1[$i1]->order == $curOrder)
{
//Do what I need to do
break;
}
elseif($a1[$i1]->order > $curOrder)
{
//We know the order won't exist in this array.
break;
}
$i1++;
}
while ($i2 < $c2)
{
if($a2[$i2]->order == $curOrder)
{
//Do what I need to do
break;
}
elseif($a2[$i2]->order > $curOrder)
{
break;
}
$i1++;
}
}
Basically you need to sort each array and find the maxorder, then you loop over the order index and print the items with the given order. This is O(N Log(N)) because of the sorting where N = max number of elements
Here is some pseudo code
sort each array (in php use usort) - O(N log(N))
find maxorder (iterate over each) - O(N)
create an array each index
get the length of each index and store
$a1 = usort($people, function(){})
$a2 = usort($places, function(){})
$a3 = usort($things, function(){})
$c1 = count($a1)
$c2 = count($c2)
$c3 = count($c3)
$i1 = 0
$i2 = 0
$i3 = 0
// itertor over order
for ($curOrder ... $maxorder) {
// while $a1 is on current order and its index is in bound
while ($i1 < $c1 && $a1[$i1]->order == $curOrder) {
echo $a1[$i1]->value;
$i1++;
}
while ($i2 < $c2 && $a2->order == $curOrder) {
echo $a2[$i2]->value;
$i2++;
}
while ($i3 < $c3 && $a3->order == $curOrder) {
echo $a3[$i3]->value;
$i3++;
}
}
If you reindex each array by the object's order value, then you can retrieve an object with a given order in constant time. The code retrieves all related objects in O(n) because you're looking at each element a constant number of times (notice the nested loops have been removed).
$peopleByOrder = array();
$sandwichesByOrder = array();
$restaurantsByOrder = array();
$uniqueOrderKeys = array();
foreach($people as $person) {
$peopleByOrder[$person->order] = $person;
$uniqueOrderKeys[$person->order] = 1;
}
// same for $sandwichesByOrder and $restaurantsByOrder
foreach(array_keys($uniqueOrderKeys) as $oderKey) {
if(isset($peopleByOrder[$orderKey])) {
$person = $peopleByOrder[$orderKey];
}
else if(isset($sandwichesByOrder[$orderKey])) {
$sandwich = $sandwichesByOrder[$orderKey];
}
else if(isset($restaurantsByOrder[$orderKey])) {
$restaurant = $restaurantsByOrder[$orderKey];
}
}

Convert simple string to Required Format : PHP

I would like to Convert simple string to set based on below logic
if string is 3,4-8-7,5 then I need the set as (3,8,7),(4,8,5).
The Logic behind to building the set are we need to consider ',' as OR condition and '-' as AND condition.
I am trying my best using For loop :
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}
echo $intermediate, should give final result.
This Code works correctly, Try this
<?php
$intermediate = array();
$str="";
$val='3,4-8-7,5';
$vals=str_replace(',','-',$val);
$j=1;
$arry_A = explode('-',$vals );
$str.='(';
for ($i = 0; $i < count($arry_A); $i++) {
if($j==3){
$str.=$arry_A[$i].',';
$str.='),';
$str.='(';
$j=1;
}
else
$str.=$arry_A[$i].',';
$j++;
}
echo substr($str, 0, -2);
?>

PHP: Cannot use [] for reading - but it's not [] but [$counter]

in general I think I understand what the error message means. But in my case, it's a riddle I didn't succeed in solving...
$keywords_all = array();
$count = 0;
for ($z = 0; $z < $num_results; $z++)
{
$keywords_array = explode(",", $row['free_keywords']);
for ($i = 0; $i < count($keywords_array); $i++)
{
if (in_array(strtolower(trim($keywords_array[$i])), $keywords_all))
{
$count++;
}
else
{
echo "<br />".$keywords_array[$i];
$keywords_all[$count] = $keywords_array[$i];
}
}
$row = pg_fetch_array($result);
}
So, what's wrong with that one? The error message pops up in the line
$keywords_all[$count] = $keywords_array[$i];
I have no clue, seems to be alright to me. But guess, it's again a tiny, tiny thing I've neglected... Thanks for any hints!
I was not able to reproduce your error message. I did find a bug in your code though (I am assuming that you are putting all your keywords in the $keywords_all array without any duplicates). So you should not increment $count inside your IF but instead update the $keywords_all count. See below:
if (in_array(strtolower(trim($keywords_array[$i])), $keywords_all)) {
$count = count($keywords_all);
} else {
echo "<br />".$keywords_array[$i];
$keywords_all[$count] = $keywords_array[$i];
$count++;
}
You will increment $count after storing a value to your $keywords_all array.
$keywords_all = array();
$count = 0; // what for you neet this var ?
$myRow = 'keyW1,keyW2,keyW3,keyW2';
// for ($z = 0; $z < $num_results; $z++) // there is no variable $num_results at your code so I've replaced it with constant
for ($z = 0; $z < 1; $z++)
{
// $keywords_array = explode(",", $row['free_keywords']);
$keywords_array = explode(",", $myRow);
// for ($i = 0; $i < count($keywords_array); $i++)
foreach ($keywords_array as $keyword)
{
$keyword = strtolower( trim( $keyword ) ); // some syntax sugar would be nice
if ( !in_array( $keyword, $keywords_all) )
{
echo "<br />".$keyword;
$keywords_all[] = $keyword;
}
}
// $row = pg_fetch_array($result);
}
var_dump($keywords_all);
This code would be better for you i think, but if you just want to get rid of duplicated records
array_uniq( array("1", "1", "2", "1") )
would be better solution for you.

Categories