Looping through an array

I have an array with a bunch of numbers in it.
Im trying to create an <option for all numbers (1-20) except the numbers in the arrsy, is this ok?

				for ($x = 1; $x <= $outlett_row['sum']; $x++) {
				  foreach ($Array as $position)
					  if($position != $x) { echo '<option value='.$x.'>'.$x.'</option>'; }
					}
				}

This looks like an attempted solution to the real problem. Where is this exclusion array coming from?

This… will probably not do what you want it to do. Try tracing your variables to see why.

Is this not the same question you had last week? (Create a new array based on another)

Here is the problem, I have this array

$Array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
echo '<pre>';print_r($Array);echo '</pre>';
//produces
Array ( [0] => 15, [1] => 14 )

and

for ($x = 1; $x <= 15; $x++) {
echo '<option value='.$x.'>'.$x.'</option>'; }
}

which create all the options total (1 - 15)… I am trying to alter t\it by removing the numbers in the array.
so it would show the options available ( 1-13)

You should look into the range and array_diff functions.

1 Like

Here’s an alternative user interface, add the disabled attribute to the options that are not available. They would appear in the list of options, but are not selectable.

// use in_array() to disable the ones you don't want
for ($x = 1; $x <= $outlett_row['sum']; $x++)
{
	$dis = in_array($x,$Array) ? ' disabled' : '';
	echo "<option value='$x'$dis>$x</option>\n";
}
1 Like

I just wanted to try out @rpkamp’s suggestion. It seems like a pretty good to solution me.

php

<?php
$exclude = array(10, 11);
$options = array_diff(range(1, 15), $exclude);
print_r($options);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [11] => 12
    [12] => 13
    [13] => 14
    [14] => 15
)
4 Likes

(This is… also the same answer we gave you last week :P)

2 Likes