How do I get final value of += operator in php? - php

I want to get final value of $score in the code below
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
$score = 0;
if($value === $kunci){
$score+=1;
echo $score;
}
}
but its produce value
123456789101112131415161718192021
how do I get 21 value only?

Based on what others have said: But just to show you the full code
$score = 0; //define this before the loop
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci) $score+=1; //simplify this, as I am lazy coder.
}
echo $score; //echo the final value, after the loop finishes.
Good Luck.

You need to echo after loop. As below:
$score = 0; //define this variable before loop
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci){
$score+=1;
}
}
echo $score; // echo after loop end
Hope it helps you.

Initialize $score before the loop and also print the output after loop.
$score = 0;
foreach($request->jawaban as $key => $value){
$soal = Soal::find($key);
$kunci = $soal->kunci;
if($value === $kunci){
$score+=1;
}
}
echo $score;

Related

Loop into an array with PHP

I have the following array:
$array = [
['2017-02-26', '2017-02-27'],
['2017-03-01'],
['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],
['2017-01-05', '2017-01-06', '2017-01-07']
];
I'm looking to loop into this array to have something like this:
// When several dates
From 2017-02-26 to 2017-02-27.
// When only one date
On the 2017-03-01.
What I tried:
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
echo "On the $key[$value]";
}
else {
$first = reset($array);
$last = end($array);
echo "From ".$first." to ".$last.;
}
}
But it doesn't work when there is only one date in the row.
You are looping by foreach() so it will display last echo string .Store result to one variable Eg($display) will be more easy to display that
$display = "";
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
$display .= "On the $value[0] <br>";
}
else {
$first = $value[0];
$last = $value[$count-1];
$display .= "From ".$first." to ".$last."<br>";
}
}
echo $display;
Try this:-
foreach ($array as $key => $value) {
$count = count($value);
if($count==1) {
echo "On the ".$value[0];
}
else {
$first = reset($value);
$last = end($value);
echo "From ".$first." to ".$last;
}
}
Or just copy paste this code, it will work. Your main inside array to play with is $value.

loop through $_POST variables with similar names

I have several $_POST variables, they are
$_POST['item_number1']
$_POST['item_number2']
and so on
I need to write a loop tha displays the values of all the variables (I don't know how many there are). What would be a simplest way to go about it? Also what would be the simplest way if I do know how many variables I have?
This will echo all POST parameters whose names start with item_number:
foreach($_POST as $k => $v) {
if(strpos($k, 'item_number') === 0) {
echo "$k = $v";
}
}
PHP Manual: foreach(), strpos()
If you know how many do you have:
for ($i=0; $i < $num_of_vars; $i++)
echo $_POST['item_number'.$i]."<br />";
UPDATE:
If not:
foreach($_POST as $k => $v) {
$pos = strpos($k, "item_number");
if($pos === 0)
echo $v."<br />";
}
Gets all POST variables that are like "item_number"
UPD 2: Changed "==" to "===" because of piotrekkr's comment. Thanks
try:
foreach($_POST as $k => $v)
{
if(strpos($k, 'item_number') === 0)
{
echo "$k = $v";
}
}
In the above example, $k will be the array key and $v would be the value.
if you know the number of variables:
<?php
$n = 25; // the max number of variables
$name = 'item_number'; // the name of variables
for ($i = 1; $i <= $n; $i++) {
if (isset($_POST[$name . $i])) {
echo $_POST[$name . $i];
}
}
if you don't know the number:
<?php
$name = 'item_number';
foreach ($_POST as $key) {
if (strpos($key, $name) > 0) {
echo $_POST[$key];
}
}
If you must stick with those variable names like item_numberX
foreach (array_intersect_key($_POST, preg_grep('#^item_number\d+$#D', array_keys($_POST))) as $k => $v) {
echo "$k $v \n";
}
or
foreach (new RegexIterator(new ArrayIterator($_POST), '#^a\d+$#D', null, RegexIterator::USE_KEY) as $k => $v) {
echo "$k $v \n";
}
Better to use php's input variable array feature, if you can control the input names.
<input name="item_number[]">
<input name="item_number[]">
<input name="item_number[]">
then php processes it into an array for you.
print_r($_POST['item_number']);
foreach($_POST as $k => $v) {
if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
$number = $keyMatch[1];
// ...
}
}
try:
while (list($key,$value) = each($_POST))
${$key} = trim($value);

how to count strings in php?

i have this situation"
foreach($front->getRequest()->getParams() as $key => $value){
if ($value == '1'){
$$key = $value;
}
}
echo $test1; // test1 = 1
echo $test2; // test2 = 1
....
this will give me back one or more $test = 1 where the $$key = $test and $value = 1
i want to see how many actually come back. and i was thinking to do something like: print_r(count($key)) or print_r(count($value)) but it doesn't tell me how many results are there
any ideas?
thanks
Why not just keep a counter?
$count = 0;
foreach($front->getRequest()->getParams() as $key => $value){
if ($value == '1'){
$$key = $value;
$count++;
}
}
echo $count;

PHP - Detect change on string

I have an array which i do a foreach($array as $key => $value)
in my $key i get
name[1][1]
name[1][2]
name[1][3]
name[2][1]
name[2][2]
how can I add detect when the first index changes from [1][3]->[2][1]
any help is appreciated.
What i want to achieve is this:
<h4>Header</h4>
name[1][1]
name[1][2]
name[1][3]
<h4>Header</h4>
name[2][1]
name[2][2]
<h4>Header</h4>
name[3][1]
name[3][2]
name[3][3]
name[3][4]
Don't know if it is the best option, but this is how i managed to do it.
<?php $k = 1; $flag1 = 0; $flag2 = 1;foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<?php
$endpos = strpos($option_name,']');
$asd = substr($option_name,5,$endpos-5);
$this->firephp->log($asd);
if($asd % 2)
{
if($flag1 === 0)
{
echo ' <h4>Header '. $k .'</h4>';
$flag1 = 1;
$flag2 = 0;
$k++;
}
}
else
{
if($flag2 === 0)
{
echo ' <h4>Header '. $k. '</h4>';
$flag2 = 1;
$flag1 = 0;
$k++;
}
}
?>
You can try like
foreach($name as $parent_key => $parent_value){
echo "<h4>Header</h4><br/>";
foreach($name[$parent_key] as $key=>$value)
{
echo $name[$i][$key]."<br/>";
}
}
foreach($array as $key => $value){
$valuevalues = array();
foreach($value as $val){
if($val != "" && !isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "different-than-previous";
if(!isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "equal-to-first-value";
}
}

for loop and if loop is refusing to print a varriable outside the loop?

i am facing a problem that after i created the jQuery post, i was able to receive all the data but as a one peace, so when i began rephrasing them i succeed until the final part which was the inserting into the database, where inside the for loop and if loop i am getting the value but when i wanted to start inserting them into the database i am getting null values, below is the for loop and if loop
if ($action == "insert")
{
$fields = explode("&",$data);
foreach($fields as $field)
{
$field_key_value = explode("=",$field);
$key = urldecode($field_key_value[0]);
$value = urldecode($field_key_value[1]);
$id = $row['id'];
$date1 = date("d/n/Y");
foreach ($cart->get_contents() as $item)
{
$item_id = $item['id'];
$item_name = $item['name'];
$item_price = $item['price'];
$item_qty = $item['qty'];
$item_ids = explode("-",$item_id);
for($i = 0; $i < count($item_ids); $i++)
{
$item_idn = join("",$item_ids);
}
if($key == $item_id."id")
{
$ids = $value;
echo $ids."\r\n";
}
elseif($key == "Small".$item_idn)
{
$small= $value;
echo $small."\r\n";
}
elseif($key == "large".$item_idn)
{
$large= $value;
echo $large."\r\n";
}
elseif($key == "medium".$item_idn)
{
$medium= $value;
echo $medium."\r\n";
}
elseif($key == "xlarge".$item_idn)
{
$xlarge= $value;
echo $xlarge."\r\n";
}
elseif($key == "qty".$item_idn)
{
$qty = $value;
echo $qty."\r\n";
}
elseif($key == "Total".$item_idn)
{
$subtotal = $value;
echo $subtotal."\r\n";
}
elseif($key == "finaltotal")
{
$finaltotal = $value.",";
$final = explode(",",$finaltotal);
for($i = 0; $i < count($final); $i++)
{
$totalf = $final[$i];
break 3;
}
}
}
}
}
From jQuery docs:
The .serialize() method creates a text string in standard URL-encoded notation
So on the PHP side you'll get a similar string like this:
a=1&b=2&c=3&d=4&e=5
There's no need to explode &'s (or any other hocus-pocus) you can easily access your submitted variables like:
$a = $_POST['a']; //1
Of course when you submit your data via $_GET, you need to use $_GET.
It appears as if you have a number of issues. If your jQuery is posting to your PHP script you can get all your keys/values through the $_POST array. You could get $finaltotal like this $finaltotal = $_POST['finaltotal']. If your jQuery is not POSTing, but sending them as a GET request, you can get the same value like so $finaltotal = $_GET['finaltotal'].
Also, regarding your big if/elseif block of code, I would recommend using a switch statement instead if you are going to keep your code as is.
switch($key)
{
case 'finaltotal':
//do stuff
break;
default:
//do default
break;
}
First of all, you either can use $_GET/$_POST for the submited data, as fabrik pointed out, or (if for some reason you really only have your data in $data) can use the built in function parse_str.
parse_str($data, $fields);
foreach($fields as $key => $field) {
foreach ($cart->get_contents() as $item) {
if($key == ...) {
...
}
}
}
And if I correctly understand what you are doing here, you need to move the break 3; out of your for loop:
elseif($key == "finaltotal") {
$finaltotal = $value.",";
$final = explode(",",$finaltotal);
for($i = 0; $i < count($final); $i++){
$totalf = $final[$i];
}
break 3;
}

Categories