Array editing not working correctly - php

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++.

Related

How to check if value is equal to string in array

I want to check if the value: diam-mm exist in array, if the value not exist do something.
A array can have multiple properties, property name is: [PropertyType]->[Name]
i thought i loop to the properties and check if diam-mm value exist, else do something but because of the loop he does import the value mutliple times instead of one time.
Example of one array with properties:
[2] => Array
(
[PropertyType] => Array
(
[Guid] =>
[DataType] => Text
[Name] => diam-mm
[Unit] =>
)
[BooleanValue] =>
[DateTimeValue] =>
[NumericValue] =>
[TextValue] => 400
[XmlValue] =>
[UrlValue] => 400
)
[3] => Array
(
[PropertyType] => Array
(
[Guid] =>
[DataType] => Text
[Name] => lengte-mm
[Unit] =>
)
[BooleanValue] =>
[DateTimeValue] =>
[NumericValue] =>
[TextValue] => 2000
[XmlValue] =>
[UrlValue] => 2000
)
<?php
for ($i=0; $i <count($array) ; $i++) {
if($array[$i]['PropertyType']['Name']=="diam-mm"){
// your code
}
}
?>
If you want to check if an array key matches a value you can do so using simple variable assignment. However you would need to loop through each array index item and enumarate the loop based on it's iteration.
To create the loop I would suggest using count to count the amount of items in the array. We will assign the result to a variable :
$count = count($my_array);
Do keep in mind that count only counts the number of items based on their actual count, not their array index. This means that an array with indexes starting from zero which has an index of 0-30 would return 31 as the result of count because count counted the zero index as an actual count value.
To fix this we need to subtract 1 from the result of count :
$count = $count - 1;
Then we can use the count as the number of repeats in a for loop. Where the variable $i represents the iteration that the loop is going through :
//Loop through each array index
for($i=0; $i <= $count; $i++){
//Assign the value of the array key to a variable
$value = $my_array[$i]['PropertyType']['Name'];
//Check if result string contains diam-mm
if(str_contains($value, 'diam-mm'){
echo 'The value matches!';
} else{
echo 'The value does not match!';
}
}
Try this function, i hope this answer your question...
function array_recursive_search_key_map($needle, $haystack) {
foreach($haystack as $first_level_key=>$value) {
if ($needle === $value) {
return array($first_level_key);
} elseif (is_array($value)) {
$callback = $this->array_recursive_search_key_map($needle, $value);
if ($callback) {
return array_merge(array($first_level_key), $callback);
}
}
}
return false;
}
How to use
$yourValue = "diam-mm";
$array_keymap = array_recursive_search_key_map($yourValue, $yourArray);
var_dump($array_keymap);
Output
Array
(
[0] => 0
[1] => PropertyType
[2] => Name
)

PHP For loop skips the first outcome

I'm trying to fill an array with a for loop. This is done to get the amount of pages a certain book has. but when executing the code, it skips the first object in the array. Can anyone tell me why? (I thought it was because $i starts at 1 instead of 0 but that doesn't seem to change anything)
if(!empty($article['finishing'])){
$numPages = $article['copies'];
$arrayIndexNumber = [];
for($i=1; $i <= $numPages; $i++){
$arrayIndexNumber[] = $i;
}
if(count($arrayIndexNumber) >= 1 ){
if(count($arrayIndexNumber) == 1){
$output['attributes']['EFPageRange'] = 1;
$print_jobs[$article['id']][] = $output;
}
if(count($arrayIndexNumber) > 1){
$comma_separated1 = implode(", ", ['1', $article['copies']]);
$output['attributes']['EFPageRange'] = $comma_separated1;
$print_jobs[$article['id']][] = $output;
}
array_shift($arrayIndexNumber);
array_pop($arrayIndexNumber);
$comma_separated2 = implode(", ", $arrayIndexNumber);
$output['attributes']['EFPageRange'] = $comma_separated2;
if(count($arrayIndexNumber) >= 2){
$print_jobs[$article['id']][] = $output;
}
}
$article['file_url'] = 'i has finishing';
$output['attributes']['username'] = $article['file_url'];
}
above code outputs:
[0] => Array
(
[attributes] => Array
(
[title] => 277569
[EFPrintSize] => a4
[num copies] => 1
[num pages] => 119
[EFPCName] => 80
[EFDuplex] => TopTop
[EFPageRange] => 1, 119
)
)
instead of:
[0] => Array
(
[attributes] => Array
(
[title] => 277564
[EFPrintSize] => a4
[num copies] => 1
[num pages] => 45
[EFPCName] => 80
[EFDuplex] => false
[EFPageRange] => 1, 45
[username] => i has finishing
[EFColorMode] => Grayscale
)
)
Your first array element is deleted because of array_shift:
array_shift($arrayIndexNumber);
array_shift
array_shift — Shift an element off
the beginning of array
Debug your code:
for($i=1; $i <= $numPages; $i++){
$arrayIndexNumber[] = $i;
}
echo '<pre>';
print_r($arrayIndexNumber); // Check what the array returns
php array indexes starts to count from zero
for($i=1; $i <= $numPages; $i++)
^^^
change it to $i=0

Increment array value by 1 in 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]

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.

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;
}

Categories