Increment array value by 1 in php - php

I have a simple array $rating=[0,0,0,0,0]; and I need to increment the values by 1. I have a value $val=2. if value matches to 2 then I want to increment $rating[1] value by 1. (Just example, but increment is not happening)
$rating=[0,0,0,0,0];
$val = 2;
if($val ==2){
$rating[1]++;
}
after this $rating[1] suppose to increment and has to become 1(i.e $rating must be [0,1,0,0,0]). its not working!!

It's working Fine. like below
<?php
$rating = array('0','0','0','0','0');
$val = 2;
if($val ==2){
$rating[1]++;
}
print_r($rating);
?>
Output:
Array ( [0] => 0 [1] => 1 [2] => 0 [3] => 0 [4] => 0 )

I got to know what mistake I was doing! It was inside while loop and thas y getting initiated again and again. The best way
$rating=[0,0,0,0,0];
$val = 2;
if($val ==2){
$rating[1]++;
}
echo $rating;
this gives the output [0,1,0,0,0]

Related

sum and divide depends on input php

I have a form like this
for($x=0;$x<8;$x++){
echo "<input name='test[]'> <br>";
}
then i'm input, and i get this result
Array
(
[0] => 1
[1] => 2
[2] => 0
[3] => 0
[4] => 0
[5] =>
[6] => 0
[7] =>
)
I want to sum then divide it. I'm using array_sum to sum it. Now the problem, how can i divide it depends on my input(s) not the many of input field(s) and i don't want count the zero as input.
so it will become something like this
(1+2) / 2
how can i achieve that? sorry for my bad english.
If you want only non-zero values to be counted, you'll need to filter those zero and empty values away. You can still use array_sum(), to sum the array, but you'll need a filter on your count(), because count() will count all elements, regardless of the content (except null-values).
array_filter() takes care of this. So you'll simply need this
echo array_sum($myArray) / count(array_filter($myArray)); // Outputs 1.5 with your sample-array
Live demo
http://php.net/count
http://php.net/array_filter
Try This:
$myArray = Array
(
[0] => 1
[1] => 2
[2] => 0
[3] => 0
[4] => 0
[5] =>
[6] => 0
[7] =>
)
$countArray = 0;
foreach($myArray as $v){
if($v !== 0 || $v !== ''){ //skip if 0 or empty
$countArray++
}
}
$result = array_sum($myArray) / $countArray;
You may use this PHP custom Function
<?php
/* Function for check and remove blank and empty element from array */
function remove_blank($arra)
{
$newArr = array();
$total = count($arra);
for($i = 0; $i <= $total; $i++)
{
if($arra[$i] != "" && $arra[$i] >= 0)
{
$newArr[] = $arra[$i];
}
}
echo "<pre>";
print_r($newArr);
}
$arra = array(1, 2, 0, 0,'', 0,'');
remove_blank($arra);
?>

Add an integer to a key of an array PHP

let's say we have the following array:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 1 )
I want to reprint this array, with the [4]th key having an additional +1, like so:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 2 )
Then again:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 3 )
EDIT: The solutions given below work, however, my code does not increment the 4th key:
$filew = 'databases/stocktakemain.csv';
$getfilecont = file_get_contents($filew);
$writes = explode(",", $getfilecont);
++$writes[4];
Is there an issue with this code? Does this not apply when creating arrays through explode?
you can use the ++ to incremente in 1 your 4th array value
<?php
$array[0] = 123456;
$array[1] = 'Rothmans Blue';
$array[2] = 40;
$array[3] = 'RB44';
$array[4] = 1;
echo ++$array[4] . "<br>\n";
echo ++$array[4] . "<br>\n";
echo ++$array[4] . "<br>\n";
?>
At the end of your code, you can put
Array[4] == Array[4] + 1;
This will print out 10 arrays with that last key being an incrementing number, change the $max to make it bigger/smaller.
$max = 10;
for( $i=1; $i<=$max; $i++ ) {
print_r( array(
123456,
'Rothmans Blue',
40,
'RB44',
$i
));
}
In this case, you don't actually need to declare the key values as PHP considers the index of a value in an array to be its key.
You might try something like this if you want to print the values, then increment:
$myArray = array(123456, "Rothmans Blue", 40, "RB44", 1);
for ($i= 0; $i < 3; $i++)
{
foreach ($myArray as $key => $value)
{
print $key . " : " . $value;
if ($key == 4)
{
print "\n";
$myArray[$key] += 1; // Make sure to modify the original array, not the one you passed in as it is passed by reference.
}
}
}
If you want to increment and then print, move the print statement to the bottom of the foreach loop.
You can use end($array) function and get the last element and then add.

Array editing not working correctly

OK so here's my code to edit a specific entry within the array, and the array layout is below.
$counter = 0;
foreach($_SESSION['cart'] as $listitem){
if ($listitem[0] == $_POST['product']){
if ($listitem[1] <= $_POST['remove']){
$remove = array($listitem[0], 0);
$_SESSION['cart'][$counter] = $remove;
} else {
$result = $listitem[1] - $_POST['remove'];
$remove = array($listitem[0], $result);
$_SESSION['cart'][$counter] = $remove;
}
}
$counter = $counter++;
}
Here's my $_SESSION['Cart'] Array layout
Array(
- [0] => Array ( [0] => 8 [1] => 0 )
- [1] => Array ( [0] => 10 [1] => 0 )
- [2] => Array ( [0] => 8 [1] => 1 )
)
Either my understanding of the array is wrong with this line of code:
$_SESSION['cart'][$counter]
Or my counter will not count:
$counter = $counter++;
since the only value it keeps editing the first entry [0]
Can anybody see where I've went wrong?
$counter = $counter++ will do nothing.
$counter++ increments the value of $counter, but evaluates to its current value (the one it had before incrementing). That way, you're setting $counter to have the value of itself, and that doesn't usually do much.
Simply do $counter++ instead.
(Additional info: there's also the pre-increment operator, ++$counter, which increments the variable and returns it new value.)
$counter = $counter++ will set $counter to its current value and then increment it by one. It is a redundant statement. If you do intend to just increment the variable $counter by 1 then just use $counter++.

Code not returning expected results

There is $sFactorGrades which I need to retrieve the 0th element from based on the GradeID and the CommutatorID, which is the 1st and 2nd element in the array respectively.
The GradeID and the CommutatorID is passed as parameters to the function.
The code that I have written is not returning the value which I know is present.
Any recommendations are welcome.
Here is my code:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[i][1]) == $commuatorID && intval($sFactorGrades[i][2]) == $gradeID) {
return $sFactorGrades[i][0];
} else {
return 0;
}
}
}
Here is my data:
Array (
[0] => Array (
[0] => Maximum S Factor
[1] => Commutator ID
[2] => Grade ID
)
[1] => Array (
[0] => 0.6
[1] => 1
[2] => 2
)
[2] => Array (
[0] => 0.6
[1] => 1
[2] => 3
)
[3] => Array (
[0] => 0.6
[1] => 1
[2] => 4
)
)
Here is my result:
0
I suspect the reason for your loop always returning 0 is that you're passing i as the incrementing variable, and not the correct one: $i. Typos can be devastating... If it still doesn't work, feel free to update your post.
Edit: A tip is to insert this at the top of your page while in development stage:
ini_set('display_errors','On');
error_reporting(E_ALL);
In this case, it should give an undefined index error or similar.
The problem with your code is that you return too early. When your code encounters a return statement, it stops the iteration. You need to move the return statement outside the loop to prevent this from happening.
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[$i][1]) == $commuatorID &&
intval($sFactorGrades[$i][2]) == $gradeID) {
return $sFactorGrades[$i][0];
}
}
return 0;
}
If your code reached the last return, then it means that the if condition was never satisfied. For getMaximumSFactor (1, 2), this should return 0.2.
Demo
$sFactorGrades[i] need to be $sFactorGrades[$i].
Also it worth to use foreach() instead of normal for().
But thats not all. You need to check all values in array before returning result:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
foreach($sFactorGrades as $key=>$value){
if (intval($value[1]) == $commuatorID && intval($value[2]) == $gradeID) {
return $value[0];
}
}
return 0;
}

PHP: Finding the next and previous values of an Array, when there may be "missing" indexes

I'm working with some data which is being retrieved from my database. It's placed into a 2-dimensional* array and manually sets the index based upon the ID of the data in the database.
* It's more than two-dimensional, but I only need to work with 2 dimensions of it.
This is the Array in question:
Array
(
[error] => Boolean(false)
[results] => Array
(
[1] => Array
(
[0] => title1
[4] => title2
)
[3] => Array
(
[0] => title3
[1] => title4
[2] => title5
)
[4] => Array
(
[0] => title6
[1] => title7
[3] => title8
)
)
)
Within this Array, I only need to work with the "results" part of it, hence making the problem Array 2-dimensional.
Some voodoo-magic happens in my script and I'm told the index for the first array and the index for the second array, and then I pull the value from the second array.
Let's say that I wanted to get the value "title5". My script would tell me that I need to use index 3 and then index 2.
I've done all of that, but it's this next part of the task that I'm stuck on, and have no-idea how to even attempt.
After retrieving "title5" I want to retrieve the indexes for the next and previous item, so in this case for both "title4" and "title6". In the event of there not being a previous value (say we originally pulled "title1") then I need some way of identifying this, like with a false boolean. And likewise for if there is no "next" value either.
By retrieve the indexes I mean, for example: title4 = 3 & 1 and title6 = 4 & 0
Does anybody have any ideas how I should go about doing this? I'm not looking for someone to do the work for me necessarily, but some pointers would be greatly appreciated. In the mean time I'll keep experimenting. Thanks!
Note:
Titles aren't actually called title1, title2, etc. So I can't just decrement a number and do a search.
I edited #Jonathan Rich's answer a little bit to obtain my actual solution. Where $firstIndex and $secondIndex are the two index that I already know.
//my already known indexes
$firstIndex = 3;
$secondIndex = 2;
//
$prevIndex1 = null;
$prevIndex2 = null;
$last_was_value = false;
$nextIndex1 = null;
$nextIndex2 = null;
foreach ( $articles['results'] as $index => $value ) {
foreach ( $articles['results'][$index] as $index2 => $value2 ) {
if ( ($index == $firstIndex) && ($index2 == $secondIndex) ) {
$last_was_value = true;
} else if ($last_was_value == true) {
$nextIndex1 = $index;
$nextIndex2 = $index2;
break 2;
} else if ($last_was_value == false) {
$prevIndex1 = $index;
$prevIndex2 = $index2;
}
}
}
echo "<br />PREV: $prevIndex1 & $prevIndex2<br />";
echo "NEXT: $nextIndex1 & $nextIndex2<br />";
Sure, this is a low level solution:
$prev = null;
$last_was_value = false;
$next = null;
foreach ( $foo['results'][$index1] as $index => $value ) {
if($value == $some_result_value) {
$last_was_value = true;
} elseif($last_was_value == true && $next == null) {
$next = $index;
} elseif($last_was_value == false) {
$prev = $index;
}
}
So in the end, if prev or next are null, then your index is the first/last index respectively, and if not then those values are the sibling indexes.

Categories