How to get last value of for loop? - php

I'm trying to get the value of $row->price for the last iteration in my for loop as below
foreach ($getprices->result() as $row)
{
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
I did try the following, however it didn't appear to work
$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
if(++$i === $numItems) {
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
}
}
Any suggestions?

Use $row->price just after the loop has ended:
foreach ($getprices->result() as $row)
{
// ...
}
$lastprice = $row->price;
This is really just a trick, but it will work. If you are iterating over an array you can also do it like this:
$array = $getprices->result();
foreach ($array as $row)
{
// ...
}
$lastprice = end($array)->price; // this will work independently of any loop

Add a line $lastitem=$row right after the for statement ; it will contain the last value after the loop is finished

You can use php end to get the last value of an array.
eg;
$arr = $getprices->result();
$last = end($arr);

Related

why am i only getting the first row value in array "row" in the below code. i need all the values corresponding to the query

$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
return $row;
}
}
i have a query , which returns all the values in the table and a function to convert it into an assosiate array. But only getting the first row in the array
Because ur using return inside loop, it only take first value and return it.
$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
$arr =[]
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
array_push($arr, $val)
}
return $arr;
}
Because, you are returning the result set in the loop.
So, only the first row is returned from the loop.
As, in the first iteration, return statement is encountered, so, that function will return and control will get out of the function.
And next iterations will not loop over the result set.
We need to create an array before loop,
append results to that array
and return the array.
Corrected Code:
$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
$array = array();
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
$array[] = $row;
}
return $array;
}
Instead writing a return inside a loop, replace that line with an array push or array shift function.
Once the loop has ended return the final result obtained from array_push/array_shift.
Put your return outside the loop so only it returns only the first loop
function x($d) {
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
return $row;
}
}
You need to return outside the loop :
$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
$arr =array();
foreach ($d as $k=> $row) {
$val = $row["id"];
$cont = trimContent($row);
$arr[$k] = $row;
}
return $arr;
}

$array[$key] = $something creates a new array

I have this php code that's supposed to check how many times a single item is in an array and put the amount in the value of that key.
im asking, why does the $duplicates[$item] += 1; create a new array instead of appending it to the existing array
here is the picture of the output I get.
this is my code:
$itemQuery = $con->prepare("SELECT cart_value FROM active_carts WHERE username=:prodName");
$itemQuery->bindParam(":prodName" , $uname , PDO::PARAM_STR);
$itemQuery->execute();
$itemCount = $itemQuery->fetchAll();
$arrax = $itemCount[0]["cart_value"];
$itemArrX = explode(",", $arrax);
$inQuestion = array();
$duplicates = array();
foreach ($itemArrX as $item) {
if (in_array($item , $inQuestion)) {
$counter = 0;
if (!array_key_exists($item , $duplicates)) {
$duplicates[$item] = $counter;
// doesnt even execute
} else {
echo $duplicates[$item]; // echoes a new array every time
$duplicates[$item] += 1;
}
} else {
array_push($inQuestion, $item);
}
}
It is rather simple, you never created that item in the array.
$data[$key] = $value; //examine that.
try this $duplicates[$item] = $item;
then $duplicates[$item] += 1;
If you're just looking for a count of duplicate values, I like the suggestion about array_count_values() in the comments. That can be run through array_filter() to remove the non-duplicate values.
$itemQuery = $con->prepare("SELECT cart_value FROM active_carts WHERE username=:prodName");
$itemQuery->execute([":prodName"=>$uname]);
$itemArrX = explode(",", $itemQuery->fetchColumn(0));
$itemArrX = ["foo","bar","baz","bar","boo","baz"];
$duplicates = array_filter(array_count_values($itemArrX), function($v){return $v>1;});
$inQuestion = array_unique($itemArrX);
print_r($duplicates);
print_r($inQuestion);
Or here's a condensed version of your code which should work just fine.
$itemQuery = $con->prepare("SELECT cart_value FROM active_carts WHERE username=:prodName");
$itemQuery->execute([":prodName"=>$uname]);
$itemArrX = explode(",", $itemQuery->fetchColumn(0));
$itemArrX = ["foo","bar","baz","bar","boo","baz"];
$duplicates = [];
$inQuestion = [];
foreach ($itemArrX as $item) {
if (in_array($item, $inQuestion)) {
echo $duplicates[$item];
$duplicates[$item]++;
} else {
$duplicates[$item] = 1;
$inQuestion[] = $item;
}
}
print_r($duplicates);
print_r($inQuestion);

Data in nested foreach loops used in update query

This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)

Selected values as json_encode data

I've got two foreach() loops in my php to fetch MySQL data from 2 different dbs.
foreach ($result as $val) {
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
I want to pass the results from both foreach loops as json_encode() data.
My question is, how do I pass $number , $score and $rankas json_encode()?
I tried the below at the bottom of the code, but did not work.
$data = array();
$data[$val] = $val["tel"];
$data[$dta] = $dta["score"];
$data[$dta] = $dta["rnk"];
echo json_encode($data);
Expecting output:
[{"tel":"123456","score":"785","rnk":"135"}]
$dta and $val are only in the loops scope. You assign variables within the loop, so use them.
$data = array();
$data['tel'] = $number;
$data['score'] = $score;
$data['rnk'] = $rank;
echo json_encode($data);
You can also assign $data within your foreach loop.
$data = array();
foreach ($result as $val) {
$data['country'] = $val["count"]; //results fetched successfully
$data['tel'] = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score']= $dta["score"]; //results fetched successfully
$data['rank'] = $dta["rnk"];
}
echo json_encode($data);
try this
$data = array();
foreach ($result as $val) {
$data['tel'][] = $val["tel"];
$country = $val["count"]; //results fetched successfully
$number = $val["tel"];
}
foreach ($rslt as $dta) {
$data['score'][] = $dta["score"];
$data['rnk'][] = $dta["rnk"];
$score = $dta["score"]; //results fetched successfully
$rank = $dta["rnk"];
}
echo json_encode($data);
Added an extra [] if array size of $val["tel"],$dta["score"],$dta["rnk"] is greater than 1 else you can remove [] if array size is 1

Add string to all looped items except the last one

I'm looping through some mysql results and need to add <span id=bottom></span> to each of them except the last row. What's the easiest way of doing this?
Will I have to count rows and then use a counter and an if/else statement? Or is there an easier method?
Try something like this:
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
{
$list[] = $row;
}
$lastItem = array_pop($list);
foreach($list as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
Not very short, but that would do the trick. Alternatively you could do what you suggested:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
for($i = 0; $i < $num-1; $i++) {
$element = mysql_fetch_assoc($result);
// echo here..
}
$item = mysql_fetch_assoc($result); // fetch last item..
Best wishes,
Fabian
I'm not a PHP expert, but can you put each row in an array? That way to know the length and you can loop through the array.
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
$list[] = $row;
foreach(array_slice($list, 0, -1) as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
You can avoid copying all the data before processing it if you fetch a record in advance before printing it (or the other way round: process the previously fetched record)
foreach( $pdo->query('SELECT x FROM foo') as $r) {
if ( isset($row) ) {
echo '<span>', $row['x'], '</span>';
}
$row = $r;
}
if ( isset($row) ) {
echo $row['x'];
}

Categories