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]
}
}
Related
I have an associative array that might contain duplicates. I am trying to loop through the array and compare the current element with the next element in the array. If there is a duplicate, it should be removed.
The code below removes one instance of the element. In the test array I'm using, I have 3 duplicate part numbers, but my code only removes one. I'm left with two. I only want one to remain.
$length = count($items);
for($i = 0; $i < $length -1; $i++){
if($items[$i]['part_number'] == $items[$i+1]['part_number']){
unset($items[$i+1]);
$items = array_values($items);
}
}
What am I doing wrong here?
You need to loop backwards through the array, and delete the current item.
$length = count($items);
for($i = $length - 1; $i > 0; $i--){
if($items[$i]['part_number'] == $items[$i-1]['part_number']){
unset($items[$i]);
}
}
becuase your code is
The $ items value is in the for statement.
if you want unique array, you have to array_unique function
http://php.net/manual/en/function.array-unique.php
In your case after you unset element, $i++ in for loop, you reindexed your array and you skip one element. Add $i-- if you unset item. Or you can reindex your array after for loop.
This is also a very simple example you can start improving with.
<?php
$test = ['sample', 'sample', 'sample', 'not', 'not', 'no', 'no'];
$test2 = [];
$k = 0;
foreach ($test as $key => $value) {
if ($key == 0) {
$test2[$k] = $value;
$k++;
} else {
if ($test2[$k - 1] != $value) {
$test2[$k] = $value;
$k++;
}
}
}
$test = $test2;
var_dump($test);
One dirty hack is to check again if you have a duplicate by decreasing $i.
for($i = 0; $i < $length -1; $i++){
if($items[$i]['part_number'] == $items[$i+1]['part_number']){
unset($items[$i+1]);
$items = array_values($items);
$i--;
}
}
This way it will again test your previous value against next item in array.
So if 0==1, then next time if 0==2.
Your code did 0==1 then (2)==(3).
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.
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
I have been working with the same loop for a couple days now, and it still won't work the way I want it to. I have tried both for, foreach and while and it still refuses to work.
The code that won't work is simply:
if(!empty($_POST['submit'])){
$d = count($_POST['deleteT']);
for ($pi = 1; $pi <= $d; $pi++) {
echo "Banned ".$_POST['deleteT'][$pi]."</br>";
}
}
If deleteT has two values: 'Bob' and 'Joe' it will print:
Banned Joe
Banned
Does anyone have any insight into why this is going on?
Start your loop index with $pi = 0; and only loop while $pi < $d.
I think one of your problems is in your count statement, then with the <= condition in the for loop.
If you use count(), then just use <. Example:
$c = count($my_array);
for ($i = 0; $i < $c; $i++) {
// do stuff
}
That said, an easier way to iterate over an array is with foreach. Like this:
foreach ($my_array as $key => $val) {
// do stuff with $val or $key
}
I'm creating a program which goes through data in a array and filter outs any repeats within it and then echos out anything which isn't a repeated piece of data
for ($i = 0; $i < count($urlArray); $i++) {
for ($j = 0; $j < count($urlArray); $j++) {
if($i != $j)
{
if($urlArray[$i] !== $urlArray[$j])
echo $urlArray[$i];
}
}
}
I'm fairly certain there's something wrong but I can't quite spot it, any help with this would be great.
I dont get, how your array is structured, but whats about just array_unique()
$urlArray = array_unique($urlArray);
Or in your case (because you want to echo it
foreach (array_unique($urlArray) as $url) echo $url;
Update:
Sorry, just mixed up two functions :) Of course its array_unique() and not array_filter().
You could use built in function array_unique() to remove duplicate values in array
$result = array_unique($urlArray);
print_r($result);