Foreach into PHP array - php

I've this these array values :
$cart_item['addons'][0]['price'] = '52';
$cart_item['addons'][1]['price'] = '34';
$cart_item['addons'][2]['price'] = '12';
......
....
I want that each values are at 0 like :
$cart_item['addons'][0]['price'] = '0';
$cart_item['addons'][1]['price'] = '0';
$cart_item['addons'][2]['price'] = '0';
....
...
So I try this code :
for ($i=0; $i > 0 ; $i++) {
$cart_item['addons'][$i]['price'] = '0';
}
But it does not work. Thanks for your help !

Try this simple solution:
$count=count($cart_item['addons']);
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}

If your array is big enough, putting count() function inside for loop is being a crazy coconut. It will be much, much slower. Please use the count outside the loop:
$count = count($cart_item['addons'])
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}

You have to loop more often to achive this:
foreach($cart_item['addons'] as &$addons {
foreach($addons as &$addon) {
$addon['price'] = 0;
}
}

You can iterate over $cart_item['addons'], like so:
foreach ($cart_item['addons'] AS $key => &$value) {
$value['price'] = 0;
}
(Your code does not get executed, because $i is never changed and so is never > 0)
Also note that you need to use the reference (&$value) when changing the array in foreach loop.

There are three parts to your for loop: for(counter | test | action){}. It might be useful for you to look at this guide about for loops. You initialise your variable:
$i = 0;
then you do a logical check (the test part):
$i > 0;
If we substitute the the variable ($i) for the value it holds (0) we get:
0 > 0
which will never be true and thus you will never get to the final part (action) of the for loop:
$i++;
Instead you could make it loop until it has moved through your entire array like this:
$elementCount = count(cart_item['addons']);
for($i=0; $i < $elementCount; $i++){
$cart_item['addons'][$i]['price'] = '0';
}
Each time it loops we add one to $i until we reach the stopping condition where $i is no longer less than the number of items in the array.
It's also worth noting that PHP has a number of functions that help working with arrays.

Related

Removing duplicate code from code single/two-dimensional arrays

I'm currently facing a problem where I use an Array that contains other Arrays. Underneath is my current code. The problem however is that I execute 100 times the same code, only difference is the $anotherOtherIndex that I need for when I loop over an Array that is inside the Array I loop for.
It would help me a lot if somebody would have solution to reduce the amount of code needed, by eliminating the duplicate code.
for( $index = 0; $index < $endOfLoop; $index++ ) {
if(true) {
$myVariable = arrayWithArrays[$index][$anotherIndex]
x100...
}else{
$myVariable = arrayWithArrays[$index][$anotherIndex][$anotherOtherIndex]
x100...
}
Psuedo-code solution ( that would be perfect, and we all now perfect doesn't exist ;) ):
for( $index = 0; $index < $endOfLoop; $index++ ) {
$myVariable = arrayWithArrays[$index][$anotherIndex][?????]
}
You could set the main part and only go further into the array on the condition
for( $i = 0; $i < $endOfLoop; $i++ ) {
$myVariable = arrayWithArrays[$index][$anotherIndex]
if(false) {
$myVariable = $myVariable[$anotherOtherIndex]
}
}

php not able to get array value

I have this problem where I can't get the value from the array in the for loop but I can access it in the while loop.
I can't seem to find a answer online, so help would be much appreciated.
while ($pos = strpos($logTxt, $char, $pos))
{
$t++;
$pos += strlen($char);
$positions[$t] = $pos;
}
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[2];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
I think that this could be pretty easily fixed by using a foreach loop instead of a for loop, because it is an array.
foreach($positions as $position) {
$beginLine = $lastEndLine;
$endLine = $position;
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
If you want to use a for loop still, I believe your problem is you are only referencing the 3rd position of the array (Key 2, as arrays start at 0), not what the loop is pointing to. You could fix it by doing this
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[$i];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Your $endLine always has third element from array, because of $positions[2]. Try changing it to $positions[$i]
You base problem is using constant index in $positions[2]. But your 1st line in for loop $beginLine = $lastEndLine; will always fail because $lastEndLine is not defined yet. You can use smth like
// beginLine // endLine
$textToEcho = substr($logTxt, $positions[$i-1], $positions[$i]);
of course you need $positions[-1] set to 0 before your first loop or smth like this (it's not clear what's happening before)
UPD I've tried your code and concluded
it will not work at all if $char is the first occurence in $logTxt
it does the nearly the same as explode() function

PHP skip for loop Iteration based on a query result set

Lets say for example I have a result set from a MySQL query that has produced values: 3,5,10,11 and so forth...
I would like to iterate through a for loop in PHP but exclude the any iteration that would equal any number in results of my MySQL query.
As it stands I currently have:
for($i = 1; $i <= $num_rows; $i++)
{
if($i == 3 or $i == 5)
{
continue;
}
//Rest of loop...
As you will all appreciate hard coding these values is very time consuming and not very efficient. If any one could help it would be greatly appreciated.
If you can gather automatically those values you are currently hard coding, you can use in_array($search, $array[, $strict])
Like this :
$bypass = array(3, 5);
for($i = 1; $i <= $num_rows; $i++)
{
if( in_array($i, $bypass) )
{
continue;
}
// rest of the loop
}
PS : I prefer much more the "Dont Panic" answer, which doesn't use too many loops. (in_array will loop through the array to find your value). See his answer : https://stackoverflow.com/a/38880057/3799829
If your query results are returned as an array you can use
if(in_array($i, $results)) to do a check of $i against the results
Add your values into an array while you fetch your query results. I used PDO here for example, but you should be able to adapt it to whichever database extension you're using:
while ($row = $stmt->fetchObject()) {
$exclude[$row->value] = true;
// whatever else you're doing with the query results
}
If you use the values as keys in the array of things you want to skip, checking for them in your for loop should be more efficient than using in_array.
for($i = 1; $i <= $num_rows; $i++) {
if (isset($exclude[$i])) continue;
// rest of loop

Incrementing the array value within an array using PHP

So my end result will be this (the end result will have 48 entries):
$theArray=array(
$theArray1,
$theArray2,
$theArray3,
$theArray4,
$theArray5,
$theArray6
);
I have tried a few things but I think this is the closest, but I'm still not there yet, any help appreciated.
$i = 0;
while ($i <= 48){
$theArray[]=${"theArray".$i.","}
$i++
}
$theArray[]=${"theArray".$i};
You missed ; at the end of line:
$i = 0;
while ($i <= 48){
$theArray[]=${"theArray".$i.","}; // missed ; here
$i++; // missed ; here
}
$theArray[]=${"theArray".$i};
You have to use the function compact for create an array containing variables. Try to read the documentation http://php.net/manual/en/function.compact.php
And here are some example http://www.w3schools.com/php/func_array_compact.asp
Keep it simple as below:
<?php
$i = 0;
$theArray = array();
while ($i <= 48){
array_push($theArray, '$theArray'.$i);
$i++;
}
echo '$arr = array('.implode(',', $theArray).');';
?>
Just run this on your end. Cheers!

equivalent syntax for 'for loop' & 'while loop'?

I know basic examples about foreach to for loop and while loop since I was begin coding I didn't paying attention from the speed of executing a script which it is very very important since then I keep converting all my for each statement to for loop. If it's comes to array i'm quite confused -_-. I know it gives me down vote posting this. LIKE I'd rather let people figure things out for myself.
I just need a bit of guide using a for loop statement. How can I convert the following foreach loop to for loop/ while loop statement?
like what I seen on phpbenchmark.com as
$i = 0; while($i < 1000000) ++$i;
for($i = 0; $i < 1000000; ++$i);
CODE:
<?php
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
foreach($user as $id => $name)
{
echo '<br>Id='.$id.'Name='.$name;
}
?>
thanks alot.
EXPECTED OUTPUT LIKE foreach output:
Id=001Name=A
Id=002Name=B
Id=003Name=C
Id=004Name=D
also what if I have an array keys like
$user['AAA'] = 'A';
$user['BBB'] = 'B';
$user['CCC'] = 'C';
$user['DDD'] = 'D';
it will output as:
Id=AAAName=A
Id=AAAName=B
Id=AAAName=C
Id=AAAName=D
The for and while loops you show are simply incrementing a number, which you can use to access elements of an array if the keys of that array are equivalent to those numbers. In other words, for or while loops have nothing to do with arrays as such, you're just using a number as a key to an array.
If your array keys are not simple continuous integers, this is more problematic. You could try to construct the correct keys from your $i variable, but why? You should just iterate explicitly over the keys of the array, for which foreach is perfect. You can also do it with each or any number of other complicated ways:
while (list($key, $value) = each($array)) {
...
}
But I doubt it's going to be significantly faster than a foreach.
Something like this...
<?php
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
while (current($user)) {
echo '<br>Id='.key($user).'Name='.$user[key($user)];
next($user);
}
try this
$user['001'] = 'A';
$user['002'] = 'B';
$user['003'] = 'C';
$user['004'] = 'D';
$keys = array_keys($user);
$length = sizeof($user);
for($i=0; $i<$length; $i++) {
echo 'id: '.$keys[$i].' value: '.$user[$keys[$i]].'<br />';
}
do you wanted something like this?
$length = count($user);
for ($i = 0; $i < $length; $i++) {
print $user[$i];
}
EDIT: or something like this?
$user = array ( '001' => 'A',
'002' => 'B',
'033' => 'C' );
while( list ( $id, $name) = each ( $user) )
{
echo '<br>Id=' .$id. 'Name='.$name;
}
EDIT:also works with you r AAA = A etc case

Categories