Forum Moderators: coopster

Message Too Old, No Replies

Removing values from a loop

Removing values from a loop

         

whyyi

2:07 am on Jan 25, 2011 (gmt 0)

10+ Year Member



I'm a bit of a newbie here so sorry if this is really easy. But I'm essentially pulling data from a data feed that just gives me a list of data not formatted whatsoever. I always know the first value from the data source is going to be bogus. So I'm trying to remove it but have no clue how to remove the first value from a loop. Here's my code:

foreach($content as $result){
echo $result->getText();
}


getText(); is essentially a function used to pull the data from the data feed.

If you know another way I can always remove the first value from the loop that would be great.

Thanks and much appreciated!

jatar_k

3:31 pm on Jan 25, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$firstflag = 0;
foreach($content as $result){
if ($firstflag == 1) {
echo $result->getText();
} else {
$firstflag = 1;
}
}

whyyi

5:21 pm on Jan 25, 2011 (gmt 0)

10+ Year Member



Thanks jatar_k this works great! I'm a bit of a newbie so I'm kind of confused by why it exactly works. How does it know that it's the first entry pulled in, you can exclude the first entry by just setting a variable to 0?

rocknbil

5:36 pm on Jan 25, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or,

$count = count($content);
for ($i=1;$i<$count;$i++){
echo $content[$i]->getText();
}

$content is an array. The first member is at index zero,

$content = Array ('apples','oranges','pears');
apples=0
oranges=1
pears=2

$count will return 3. So you want to start at the second member, index 1, and iterate to one less than $count. If you go $i<=$count (all the way to 3) you get an undefined index warning.

Mikett

2:31 am on Jan 26, 2011 (gmt 0)

10+ Year Member



Is the unset(); function not appropriate for the job? If this data is being accessed as an array, I normally set the data using a loop as well. If you do not need the first value, then in the loop, set the first value to -1 that way the second value is (0).

$search = $_GET['search'];
preg_match_all("@" . $search . "@i", $content, $matches);
$results;
$i = 0;
while($matches[0][$i] !== '')
{
$j = $i--;
$results[$j] = $matches[0][$i];
$i++;
}


Say if during searching using preg_match_all(); the first result ALWAYS returns null, for a reason unknown. By declaring $j equals $i minus one, $results[-1] equals that null factory while $results[0] is the second result.

Sorry if this is completely off subject, since I really have no clue of what you are truly trying to accomplish.