PHP array loop for in foreach - php

I have some array to go through foreach. Inside, I need to generate an array of quantity.
It still brings me back in both 0-5.
The output should look like this:
$a = array(['id' => 1,'quantity' => 5,'input' => 'one'],
['id' => 2,'quantity' => 4,'input' => 'two'] );
foreach ($a as $b) {
for ($x = 0; $x <= $b['quantity']; $x++) {
$count[$x] = $x;
}
dump($b['quantity']);
dump($count);
}

Well it's hard to tell what you want to achieve, but I think your current described problem is, that you are overwriting the same array in your second loop and so it still contains 5 elements from the first loop.
Add this at the top of your foreach:
foreach ($a as $b) {
$count = [];
...
This will reset the $count array on every iteration. This might bring new problems, but that's not easy to tell by the supplied information..

Related

Accessing PHP array passed through $_POST

I passed 2 arrays through $_POST and am trying to use the data in a php function. I am able to loop through each of the arrays using a foreach loop.
However, I need to loop through one of these arrays while accessing the other one in tandem (ie, on the first element in array1, I need to access the first element of array2)--so a nested foreach loop obviously doesn't help.
I have found that I cannot access the values by numerical index, however--except the first value of the array.
Any help would be greatly appreciated.
Here is the current snippet:
$count = 1;
foreach ($quantityArray as $quantity):
if($quantity < 1){
...
$order_to_item_idArray[$count]…..
}
if($quantity > 0){
...
$order_to_item_idArray[$count]…...
}
...
$count = $count + 1;
endforeach;
You will want to use something like this to achieve what you want:
$a as $key => $c
Here (as pseudo code):
$a = array('dsa','das','asf');
$b = array('aaa','eee','ggg');
foreach ($a as $key => $c)
{
echo $c . " - " .$b[$key];
}
For your code, the line would be:
foreach ($quantityArray as $key => $quantity)

Finding entry in array and putting it first or swapping with the first array entry

I have a PHP array full of arrays and what I want to do is search through this array for the chosen entry and swap it with the first entry in the array if that makes sense...
So for my example below I have chosen Penny so I would like her to either go before Bob or swap places with Bob.
My array looks like this:
$people = array(
array('Bob', 'Wilson'),
array('Jill', 'Thompson'),
array('Penny', 'Smith'),
array('Hugh', 'Carr')
);
I have tried using array_search but I don't think I am doing it correctly.
for ($i = count($array) - 1; $i > 0; $i--) {
if ($array[$i][0] == $first_name) { // Or by whatever you want to search? in_array...?
$searched_array = array_splice($array, $i, 1);
array_unshift($array, $searched_array[0]);
}
}
This is for prepending. If you want to swap, see the answer of #IAmNotProcrastinating
function swap (&$ary,$fromIndex,$toIndex=0)
{
$temp=$ary[$toIndex];
$ary[$toIndex]=$ary[$fromIndex];
$ary[$fromIndex]=$temp;
}
foreach ($elements as $key => $element) {
/* do the search, get the $key and swap */
}

PHP Pass by reference error after using same var

Take a look to this code, and help me to understand the result
$x = array('hello', 'beautiful', 'world');
$y = array('bye bye','world', 'harsh');
foreach ($x as $n => &$v) { }
$v = "DONT CHANGE!";
foreach ($y as $n => $v){ }
print_r($x);
die;
It prints:
Array
(
[0] => hello
[1] => beautiful
[2] => harsh
)
Why it changes the LAST element of the $x? it just dont follow any logic!
After this loop is executed:
foreach ($x as $n => &$v) { }
$v ends up as a reference to $x[2]. Whatever you assign to $v actually gets assigned $x[2]. So at each iteration of the second loop:
foreach ($y as $n => $v) { }
$v (or should I say $x[2]) becomes:
'bye bye'
'world'
'harsh'
// ...
$v = "DONT CHANGE!";
unset($v);
// ...
because $v is still a reference, which later takes the last item in the last foreach loop.
EDIT: See the reference where it reads (in a code block)
unset($value); // break the reference with the last element
Foreach loops are not functions.An ampersand(&) at foreach does not work to preserve the values like at functions.
So even if you have $var in the second foreach () do not expect it to be like a "ghost" out of the loop.

Remove Array value

[0] => LR-153-TKW
[1] => Klaten
[2] => Rectangular
[3] => 12x135x97
I have an array looking like this. and I want to completely remove 12x135x97 to the mother array so how would i do this?
You can use unset($arr[3]);. It will delete that array index. Whenever you want to delete an array value, you can use PHP unset() method.
As you were asked into your comment:
basically i just want to remove all index that have "X**X" this pattern digit 'x' digit
Here is the code that you can use:
$arr = array("LR-153-TKW", "Klaten", "Rectangular", "12x135x97", "xxxx");
$pattern_matched_array = preg_grep("/^[0-9]+x[0-9]+x[0-9]*/", $arr);
if(count($pattern_matched_array) > 0)
{
foreach($pattern_matched_array as $key => $value)
{
unset($arr[$key]);
}
}
print_r($arr);
PHP has unset() function. You can use it for deleting a variable or index of array.
unset($your_var[3]);
See http://php.net/manual/en/function.unset.php
You have many options:
if you know the array key then you can do this
unset($arrayName[3]);
or if it's always at the end of your array
array_pop($arrayName);
this will remove the last value out of your array
Use unset, to find it you can do this:
for($i = 0; $i < count($array); $i++){
if($i == "12x135x97"){
unset($array[i]);
break;
}
}
Unless you know the key, in which case you can do:
unset($array[3]);
its not the most time efficient if you array is thousands of items long, but for this job it will suffice.
To turn it into a method, would make for better coding.
function removeItem($item){
for($i = 0; $i < count($array); $i++){
if($i == $item){
unset($array[i]);
break;
}
}
return $array;
}
and call it like:
removeItem("12x135x97");

how to skip elements in foreach loop

I want to skip some records in a foreach loop.
For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?
Five solutions come to mind:
Double addressing via array_keys
The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's keys.
// Initialize 25 items
$array = range( 1, 25, 1);
// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
echo $array[ $keys[ $i]] . "\n";
// echo $array[$i] . "\n"; // with continuous numeric keys
}
Skipping records with foreach
I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
Using array slice to get sub part or array
Just get piece of array and use it in normal foreach loop.
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
Using next()
If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21] doesn't work, I've checked :P) you could do this (won't work if data in array === false):
while( ($row = next( $array)) !== false){
echo $row;
}
btw: I like hakre's answer most.
Using ArrayIterator
Probably studying documentation is the best comment for this one.
// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
echo $obj->current() . "\n";
$obj->next(); // Switch to next object
}
$i = 0;
foreach ($query)
{
if ($i++ < 20) continue;
/* php code to execute if record 21+ */
}
if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.
Example:
//you have an array like that
$data = array(
'1' => 'Hello world',
'2' => 'Hello world2',
'3' => 'Hello world3',
'4' => 'Hello world4',
'5' => 'Hello world5',// you want to skip this
'6' => 'Hello world6',// you want to skip this
'7' => 'Hello world7',
'8' => 'Hello world8',
'9' => 'Hello world8',
'10' => 'Hello world8',//you want to skip this
);
//Ok Now wi make an array which contain the index wich have to skipped
$skipped = array('5', '6', '10');
foreach($data as $key => $value){
if(in_array($key, $skipped)){
continue;
}
//do your stuf
}
You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (if not, it is likely that there is some other fitting iterator available):
$recordsIterator = new RecordIterator($records);
$limited = new LimitIterator($recordsIterator, 20);
foreach($limited as $record)
{
...
}
The answer here is to use foreach with a LimitIterator.
See as well: How to start a foreach loop at a specific index in PHP
I'm not sure why you would be using a foreach for this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:
$count = 0;
foreach( $someArray as $index => $value ){
if( $count++ < 20 ){
continue;
}
// rest of foreach loop goes here
}
The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.
for($i = 20; $i <= 68; $i++){
//do stuff
}
This is better than a foreach loop because it only loops over the elements you want.
Ask if you have any questions
array.forEach(function(element,index){
if(index >= 21){
//Do Something
}
});
Element would be the current value of index.
Index increases with each turn through the loop.
IE 0,1,2,3,4,5;
array[index];

Categories