PHP skip for loop Iteration based on a query result set - php

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

Related

How to improve array_rand() function with PHP?

I use the array_rand PHP function with an array. I use it with a data fixture function wich load a set of data in a loop like this:
$random_values = array();
for ($i = 0; $i < 20; $i++) {
$random_values[] = array_rand(["1","2","3","4","5"]);
}
My result is quite always "1" in the $random_values array, the native
PHP function seems not really random, Is there another stuff to do to
improve the randomization of my algorithm ?
Notice I already know there is an official documentation here, http://php.net/manual/fr/function.array-rand.php.
How's it going? So, with array_rand, it actually returns a random key within an array. Your current code does not put the random key value into the array you want to randomize. ie echo $random_value[$random_key]... See example below, hope this helps
$random_values = array("1","2","3","4","5");
for ($i = 0; $i < 20; $i++) {
$key = array_rand($random_values);
echo $random_values[$key] . "\n";
}

Foreach into PHP array

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.

PHP - Help in FOR LOOP

I have an array and looping through it and pushing the data using for loop.
$test_data = [10,20,35,01,50,60,87,12,45,86,9,85];
Actually that's a sample data. But my data is a result similar to that which I get from PostgreSQL, a single column data.
Using the below function for $test_data.
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'] = $test_data[$x];
}
Result : {"data1":{"data": 85"}}
Here's the for loop which I use along the PostgreSQL result in the PHP.
for( $x=0; $x < pg_num_rows($query); $x++ ) {
$data['data1'] = pg_fetch_assoc($query);
}
Even here I get only the last row in the browser when I do - echo json_encode($data);
Something similar to the result what I've mentioned above.
First 9 rows are not getting inserted into the data[]. Only the last row is getting added to the array.
Please say me where I'm doing the mistake.
Thanks in advance.
Since arrays cannot have same key as index.
You need to rewrite it as ..
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'][] = $test_data[$x];
// ^^ <--- Add that.
}
As Loic suggested go with a foreach , I answered quickly so it didn't strike on my mind in the first place
foreach($test_data as $val)
{
$chart_data['data1'][] = $val;
}
You could do like this (without using pg_num_rows):
// better initialize the result array
$data = array('data1' => array());
while ($row = pg_fetch_assoc($query)) {
// here is the point, add element to the array
$data['data1'][] = $row;
}

php how to loop through array until condition is met?

I have a database table with images that I need to display. In my view, I'd like to display UP TO 10 images for each result called up. I have set up an array with the 20 images that are available as a maximum for each result (some results will only have a few images, or even none at all). So I need a loop that tests to see if the array value is empty and if it is, to move onto the next value, until it gets 10 results, or it gets to the end of the array.
What I'm thinking I need to do is build myself a 2nd array out of the results of the test, and then use that array to execute a regular loop to display my images. Something like
<?php
$p=array($img1, $img2.....$img20);
for($i=0; $i<= count($p); $i++) {
if(!empty($i[$p])) {
...code
}
}
?>
How do I tell it to store the array values that aren't empty into a new array?
you could do something like:
$imgs = array(); $imgs_count = 0;
foreach ( $p as $img ) {
if ( !empty($img) ) {
$imgs[] = $img;
$imgs_count++;
}
if ( $imgs_count === 10 ) break;
}
You can simply call array_filter() to get only the non-empty elements from the array. array_filter() can take a callback function to determine what to remove, but in this case empty() will evaluate as FALSE and no callback is needed. Any value that evaluates empty() == TRUE will simply be removed.
$p=array($img1, $img2.....$img20);
$nonempty = array_filter($p);
// $nonempty contains only the non-empty elements.
// Now dow something with the non-empty array:
foreach ($nonempty as $value) {
something();
}
// Or use the first 10 values of $nonempty
// I don't like this solution much....
$i = 0;
foreach ($nonempty as $key=>$value) {
// do something with $nonempty[$key];
$i++;
if ($i >= 10) break;
}
// OR, it could be done with array_values() to make sequential array keys:
// This is a little nicer...
$nonempty = array_values($nonempty);
for ($i = 0; $i<10; $i++) {
// Bail out if we already read to the end...
if (!isset($nonempty[$i]) break;
// do something with $nonempty[$i]
}
$new_array[] = $p[$i];
Will store $p[$i] into the next element of $new_array (a.k.a array_push()).
Have you thought about limiting your results in the sql query?
select * from image where img != '' limit 10
This way you are always given up to 10 results that are not empty.
A ẁhile loop might be what you're looking for http://php.net/manual/en/control-structures.while.php

filtering out repeats

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

Categories