Add an integer to a key of an array PHP - 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.

Related

I want to make a key value pair of numeric array in PHP on the base of index

foreach($manualsArray as $manuls){
for($i=0;$i<=count($manuls);$i++){
if($i/2 == 0){
$manuls = 23;
print($manuls);
}
else{
$manualsArray= 98;
print($manualsArray);
}
print($manualsArray);
}
}
I want to create key value pairs according to index like 0 is key 1 is value 2 is key 3 is value and so on.
the sample input is write below
Array
(
[0] => Array
(
[0] => Faucet Centers
[1] => 6, 4, 13, 12, 7, 10, 14, 16, 8, 5, 9, 15, 11 in.
[2] => Flow Rate (GPM)
[3] => 1.2
[4] => Height
[5] => 5.875 in.
[6] => Max Deck Thickness
[7] => 2.25 in.
[8] => Spout Height
[9] => 3.625 in.
[10] => Spout Reach
[11] => 5 in.
)
)
You can achieve this by changing your loop to increment by 2 each time and take $i as the key and $i+1 as the value...
$output = [];
foreach($manualsArray as $manual){
$m = [];
for ( $i = 0; $i < count($manual); $i+=2 ) {
$m [$manual[$i]] = $manual[$i+1];
}
$output [] = $m;
}
print_r($output);
you can use array_chunk()
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
echo 'key: ' . $pair[0] . ' is value: '. $pair[1] . "<br>/n";
}
}
or if you want an associative array
$result_array = [];
foreach($manualsArray as $manuls){
foreach( array_chunk($manuls, 2) as $pair) {
$result_array[] = [$pair[0] => $pair[1]];
}
}
var_export($result_array);
https://www.php.net/manual/en/function.array-chunk.php
Use modulo for that:
<?php
$newarray = array();
foreach($yourarray[0] as $id => $val){
if($id % 2 == 0){
$last_index = $val;
}else{
$newarray[$last_index] = $val;
}
}
?>
I assume that your array is the one you have given, so it's 2-dimensional.
If not, use $yourarray instead of $yourarray[0].

PHP: Array Convert comma separated string to int

I just tried to parse my array that contains numbers separated with comma into numbers without the comma, but still in array form. But it didn't work.
My code:
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
print_r($arrTot);
Array result:
Array
(
[0] => 10,000
[1] => 100,000
[2] => 200,000
)
My desired output was to erase the comma in all number:
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)
I've tried with something just like this but it seems not even close with my desired output:
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) {
$valTot=str_replace( ',', '', $arrTot[$i]);
print_r($valTot);
}
Is there any way to solve this problem?
Thanks.
You can use array_walk to process each of the values in the array:
$arrTot = array('10,000', '100,000', '200,000');
array_walk($arrTot, function (&$v) {
$v = str_replace(',', '', $v);
});
print_r($arrTot);
Output:
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)
Demo on 3v4l.org
you might assign new value to current variable.
$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) {
$arrTot[$i]=str_replace( ',', '', $arrTot[$i]);
}
print_r($arrTot);
If you want the desired output, you need to replace the elements in the main array without comma.
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
foreach ($arrTot as $key => $aTot) {
$arrTot[$key] = str_replace(',','',$arrTot[$i);
}
var_dump($arrTot);
Try this-
echo "<pre>";
$arr = array('10,000','100,000','200,000');
print_r($arr);
//result
Array
(
[0] => 10,000
[1] => 100,000
[2] => 200,000
)
foreach ($arr as $key => $value) {
$new[] = str_replace(',','',$value);
}
print_r($new);
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)
try this ,
$arr = ['10,000','100,000','200,000'];
foreach($arr as $key=>$val){
$arr[$key] = (int)str_replace(',','',$val);
}
var_dump($arr);
You could simply use str_replace to achieve desired result
$arrTot = array('10,000', '100,000', '200,000');
foreach($arrTot as $key => $value){
$arrTot[$key] = str_replace(",","",$value);
}
print_r($arrTot);

PHP Array how to make it so that all arrays will have the same length

I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?
My Array:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
Expected output:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
[Cake] => ''
[Brownies] => ''
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
The array size is not limited to only two arrays. Is this even possible and if so how?
I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = [];
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . (isset($row["Session 2"]) ? $row["Session 2"] : "") . "</td>"; //Old school
echo "<td>" . ($row["Food"] ?? "") . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}

Comparing 2 arrays and adding similar values

I have 2 arrays in PHP. One of them holds a list of dates, the other a list of numbers.
Array1
(
[0] => 2010-06-14
[1] => 2010-06-14
[2] => 2010-06-14
[3] => 2014-01-26
[4] => 2014-01-26
)
Array2
(
[0] => 120
[1] => 100
[2] => 60
[3] => 140
[4] => 30
)
The value [0] in Array2 belongs with the date [0] in Array1. What I am trying to do is add all of the values in Array2 together, based on the date. Any dates that match should have their values added together. So for example at the end I would like something like:
$date = 2010-06-14;
$value = 280;
$date = 2014-01-26;
$value = 170;
...and so on.
I've searched though the site but was unable to find exactly what I needed. Any help would be appreciated...
You can iterate $values, and get the corresponding date from $dates to use as the key in your result array.
foreach ($values as $key => $value) {
$result[$dates[$key]] = $value + ($result[$dates[$key]] ?? 0);
}
The output will be like this:
array (size=2)
'2010-06-14' => int 280
'2014-01-26' => int 170
$sum=0; // New Element
$Array3[][]=0; // New 2D array
$p=0; // Counter for 2D array
for($i=0;$i<5;$i++) // Single loop for traversing
{
$date=Array1[$i]; // Start for a date
while($date==Array1[$i]){ // For for Similar date
$sum=$sum+Array2[$i]; // Adding values of similar date
$i++; // Increment array
}
$Array3[$p]["date"]=$date; // Array3 date element
$Array3[$p]["sum"]=$sum; // Array4 date element
$i--; // Reducing a value which is incremented in while loop
}
Array3 is like
Array3
(
[0] => array( 'date' => " ",'sum' => " ")
[1] => array( 'date' => " ",'sum' => " ")
)
Are you trying to count all of the values in Array2 that have an entry in Array1 that matches some predefined target value?
If so, this for loop version should work:
private function forLoopVersion($array1, $array2, $target) {
$result = 0;
for ($i = 0; $i < count($array1); ++$i) {
if ($array1[$i] == $target) {
$result += $array2[$i];
}
}
return $result;
}
Also, this foreach loop version might work, but I do not know if the $key for $array1 can be used to index an element in $array2. You could try it:
private function foreachLoopVersion($array1, $array2, $target) {
$result = 0;
foreach ($array1 as $key => $value) {
if ($value == $target) {
$result += $array2[$key];
}
}
return $result;
}
$newArray = array();
for($i = 0; $i < count(Array1); $i++) {
$newArray[$Array1[$i]] = $Array2[$i];
}
echo $newArray[$date1] + $newArray[$date2];
Put the dates as keys to for easy math.

Increment integer in set range

If I want to loop through an array and then use them as looped increment counters, how would I do that?
E.g. I have up to 5 values stored in an array. I want to loop through them, and in the forst loop I want to use a specific value, then for the second another specific value.
Pseudo code below, but how do I bring in the second array into the picture? The first range is going to dynamic and empty or have up to 5 values. The second will be fixed.
$array = array(2,6,8); // Dynamic
$array2 = array(11,45,67,83,99); Fixed 5 values
foreach ($array as $value) {
// First loop, insert or use both 2 and 11 together
// Second loop, insert or use both 6 and 45
// Third loop, insert or use both 8 and 67
}
Use $index => $val:
foreach ($array2 as $index => $value) {
if ( isset($array[ $index ]) ) {
echo $array[ $index ]; // 2, then 6, then 8
}
echo $value; // 11, then 45, then 67, then 83, then 99
}
See it here in action: http://codepad.viper-7.com/gpPmUG
If you want it to stop once you're at the end of the first array, then loop through the first array:
foreach ($array as $index => $value) {
echo $value; // 2, then 6, then 8
echo $array2[ $index ]; // 11, then 45, then 67
}
See it here in action: http://codepad.viper-7.com/578zfQ
You can try this-
foreach ($array as $index => $value) {
echo $array[ $index ]; // 2, then 6, then 8
echo $array2[ $index ]; // 11, then 45, then 67
}
Here's a clean and simple solution, that does not uses useless and heavy non standard libraries:
$a = count($array);
$b = count($array2);
$x = ($a > $b) ? $b : $a;
for ($i = 0; $i < $x; $i++) {
$array[$i]; // this will be 2 the first iteration, then 6, then 8.
$array2[$i]; // this will be 11 the first iteration, then 45, then 67.
}
We just use $i to identify the same position of the two arrays inside the main for loop in order to use them together. The main for loop will iterate the correct number of times so that none of the two arrays will use undefined indexes (causing notices errors).
Determine the minimum length of both arrays.
Then loop your index i from 1 to the minimum length.
Now you can use the i-th element of both arrays
Here is what I think you want:
foreach($array as $value){
for($x = $value; $array[$value]; $x++){
//Do something here...
}
}
You can use a MultipleIterator:
$arrays = new MultipleIterator(
MultipleIterator::MIT_NEED_ANY|MultipleIterator::MIT_KEYS_NUMERIC
);
$arrays->attachIterator(new ArrayIterator([2,6,8]));
$arrays->attachIterator(new ArrayIterator([11,45,67,83,99]));
foreach ($arrays as $value) {
print_r($value);
}
will print:
Array ( [0] => 2 [1] => 11 )
Array ( [0] => 6 [1] => 45 )
Array ( [0] => 8 [1] => 67 )
Array ( [0] => [1] => 83 )
Array ( [0] => [1] => 99 )
If you want it to require both arrays to have a value, change the flags to
MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC
which will then give
Array ( [0] => 2 [1] => 11 )
Array ( [0] => 6 [1] => 45 )
Array ( [0] => 8 [1] => 67 )

Categories