php Switch/case doesn't work - php

I tried to find my answer in the other switch/case question. But i don't find the solution.
I got a switch that split my date values in 4 different quarters.
But when i want to print it out, it doesn't work. I don't know what i'm doing wrong.
is this a typo or?
Thanks in advance.
MY CODE
while (odbc_fetch_row($result)) { // while there are rows
$overweight = odbc_result($result, "Weight1") - 44000;
//$total_overweight += $overweight;
$date = date("Y-m-d", strtotime(odbc_result($result, "Date1")));
$companies[] = odbc_result($result, "String3");
$weight = odbc_result($result, "Weight1");
$item['nrplaat'] = odbc_result($result, "String1");
$item['tptcode'] = odbc_result($result, "String3");
$item['chrononr'] = odbc_result($result, "String15");
$item['projectcode'] = odbc_result($result, "String4");
$item['projectnaam'] = odbc_result($result, "String8");
$item['1eweging'] = $weight;
$item['overweighted'] = $overweight;
$item['date'] = $date;
$item['2eweging'] = odbc_result($result, "Weight2");
$item['netto'] = odbc_result($result, "Nett");
switch($weight){
case($weight > '44000' && $weight <= '44500'):
$item['class'] = 'lichtgroen';
case($weight > '44500' && $weight <= '45000'):
$item['class'] = 'groen';
case($weight > '45000' && $weight <= '46000'):
$item['class'] = 'donkergroen';
case($weight > '46000' && $weight <= '47000'):
$item['class'] = 'bruingroen';
case($weight > '47000' && $weight <= '48000'):
$item['class'] = 'lichtbruin';
case($weight > '48000' && $weight <= '49000'):
$item['class'] = 'bruin';
case($weight > '49000' && $weight <= '50000'):
$item['class'] = 'lichrood';
case($weight > '50000'):
$item['class'] = 'rood';
}
switch($date){
case($date > $s_year.'-'.$quart1 && $date <= $s_year.'-'.$quart2):
$item['quarter'] = '1'; //kwartaal 1
case($date > $s_year.'-'.$quart2 && $date <= $s_year.'-'.$quart3):
$item['quarter'] = '2'; ////kwartaal 2
case($date > $s_year.'-'.$quart3 && $date <= $s_year.'-'.$quart4):
$item['quarter'] = '3'; ////kwartaal 3
case($date > $s_year.'-'.$quart4 && $date <= $s_year.'-'.$end):
$item['quarter'] = '4'; ////kwartaal 4
}
//$item['quarter'] = 1; WHEN I DO THIS, ALL RESULTS WILL PRINT OUT!!!
switch($item['quarter']){
case '1':
print "<tr>\n";
print " <td>" . $item['nrplaat'] . "\n";
print " <td>" . $item['tptcode'] . "\n";
print " <td>" . $item['chrononr'] . "\n";
print " <td>" . $item['projectcode'] . "\n";
print " <td>" . $item['projectnaam'] . "\n";
print " <td>" . $item['1eweging'] . "\n";
print " <td>" . "<span class=\"status\">".$item['class']."</span>" ."\n";
print " <td>" . $item['overweighted'] . "\n";
print " <td>" . $item['date'] . "\n";
print " <td>" . $item['2eweging'] . "\n";
print " <td>" . $item['netto'] . "\n";
print "</tr>\n";
break;
}
}

Use break;
case($date > $s_year.'-'.$quart1 && $date <= $s_year.'-'.$quart2):
$item['quarter'] = '1';
break;

Perhaps it's because you don't have break; in each switch case.
Try to add some break;
See here for switch in php.

You should add a break; statement at the end of each case.

You should add 'break' after 'case'. it is very important if you have some 'case'. Please understand the concept of switch statements, you can learn from http://php.net/manual/en/control-structures.switch.php.
If you have some 'case' and you don't use 'break', it mean the next case will be proceed too. If you using 'break' after 'case', the switch process will finish and not proceed to next case. Maybe you should learn about 'continue' too :)

Related

PHP Comparing 0 does not work

I'm trying to set a checkbox as checked in php based on an hour fields from a comma separated value string. It works well for 1-23 but for some reason hour 0 always displays as checked:
<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
The problem is straightforward; look at the outer loop:
for ($hour = 0; $hour <= 23; $hour++) {
Consider only the first iteration, so $hour is int(0). Further in the code:
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
Pay close attention to the loop condition:
$h <= count($myhours)
Consider the last iteration of that loop, so $h equals the size of your array.
if ((int)$hour == (int)$myhours[$h]) {
At this point $myhours[$h] is undefined because the array index is out of bounds (and a notice would have been emitted) and so (int)$myhours[$h] becomes (int)null which is int(0). The comparison is therefore always true when $hour has the value of int(0).
The solution is to change the loop condition to:
$h < count($myhours)
Not exactly and answer, but your code could be reduced to this:
$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';
}
No need for a second loop and more variables here. Also be aware to not output values from $_REQUEST directly without any check.
Demo
Try before buy
Problem solved. It was actually the count($myhours) that was causing the problem. Basically even with an empty string it still returns an array with 1 element. Changed to check if count($myhours) > 1 and everything is working as expected:
<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 1) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>

Why won't my page refresh?

I have a small time slot booking system, where I can click a link called: Reserve, and then I reserve that given time.
However, the page doesn't refresh after I've clicked on reserve. Therefore it's possible for a user to click the same reserve link twice. Whitch they shouldn't be able to.
if (isset ( $_GET ['reserved'] )) {
$sqlreserve = "INSERT INTO calendar (eventDate, timeslot) VALUES ('" . $dateToCompare . "','" . intval($_GET['t']) . "');";
$resultreserve = mysqli_query ( $mysqli1, $sqlreserve );
if ($resultreserve) {
header('Location: '.$_SERVER['PHP_SELF']);
} else {
echo "Event Failed to add";
}
}
If my insert works, then I call: header('Location: '.$_SERVER['PHP_SELF']);
I'm working on localhost, if that has anything to say?
EDIT:
The way I create my links and the text saying that a slot is booked is like this:
if (mysqli_num_rows ( $result ) == 0) {
echo "<a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $month . "&day=" . $day . "&year=" . $year . "&t={$time}&v=true&f=true&reserved=true'><h3 style='color: rgb(255,0,0);'>Reserve</h3></a>";
} else {
echo "<h3>Not Available, taken by:</h3>";
while ( $row = mysqli_fetch_array ( $result ) ) {
echo "<br />";
}
}
EDIT. My Error:
Cannot modify header information - headers already sent by (output started.....)
for($i = 1; $i < $numDays; $i ++, $counter ++) {
$timeStamp = strtotime ( "$year-$month-$i" );
if ($i == 1) {
$firstDay = date ( "w", $timeStamp );
for($j = 0; $j < $firstDay; $j ++, $counter ++) {
echo "<td> </td>";
}
}
if ($counter % 7 == 0) {
echo "</tr><tr>";
}
$monthstring = $month;
$monthlength = strlen ( $monthstring );
$daystring = $i;
$daylength = strlen ( $daystring );
if ($monthlength <= 1) {
$monthstring = "0" . $monthstring;
}
if ($daylength <= 1) {
$daystring = "0" . $daystring;
}
$todaysDate = date ( "m/d/Y" );
$dateToCompare = $monthstring . '/' . $daystring . '/' . $year;
echo "<td align='center' ";
if ($todaysDate == $dateToCompare) {
echo "class='today'";
} else {
$sqlCount = "SELECT * FROM calendar WHERE eventDate='" . $dateToCompare . "'";
$noOfEvent = mysqli_num_rows ( mysqli_query ( $mysqli1, $sqlCount ) );
if ($noOfEvent >= 1) {
echo "class='event'";
}
}
echo "><a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $monthstring . "&day=" . $daystring . "&year=" . $year . "&v=true'>" . $i . "</a></td>";
}
The line affected is:
echo "><a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $monthstring . "&day=" . $daystring . "&year=" . $year . "&v=true'>" . $i . "</a></td>";
It is in another file where I have my calendar, in which I have links to the specific day that I wan't to book the timeslots fore:
Try this..
header('Location: '.$_SERVER['PHP_SELF']);
exit;
I think your code is continuing...
A more in-depth explanation can be found here: Why I have to call 'exit' after redirection through header('Location..') in PHP?
EDIT
It's clear now that Milen Georgiev answer is correct. You output content to the browser before you reach the header(); You need to move the if statement in the top part of your PHP code to avoid the header content error.
if (isset ( $_GET ['reserved'] )) {
$sqlreserve = "INSERT INTO calendar (eventDate, timeslot) VALUES ('" . $dateToCompare . "','" . intval($_GET['t']) . "');";
$resultreserve = mysqli_query ( $mysqli1, $sqlreserve );
if ($resultreserve) {
header('Location: '.$_SERVER['PHP_SELF']);
exit;
} else {
echo "Event Failed to add";
}
}
Do you send(output/echo) anything before header('Location: '.$_SERVER['PHP_SELF']); ?
If that is the case, you will have to turn the object buffer on. Using header, you always have to send the headers first or it will not work.

PHP: Undefined offset in for loop

While making a photo gallery I encountered a problem. With every photo I try to show how many comments it has, however if a photo has 0 comments it will give me an 'undefined offset' error. I have no idea what I am doing wrong because it does show that there are 0 comments.
This is the code of what is relevant to the problem:
(The problem occurres in the line: if($reacties[$i]==0){)
if((isset($_GET['vanafFoto'])) AND (intval($_GET['vanafFoto']>=0)) AND (intval($_GET['vanafFoto'] < $countFotos))){
$begin = intval($_GET['vanafFoto']);
if(($begin + $aantalFotos) <= $countFotos){
$eind = ($begin + $aantalFotos);
} // end if
else {
$eind = $countFotos;
} // end else
} // end if
else {
$begin = 0;
$eind = $aantalFotos;
} // end else
$countFotos = count($fotoArray);
// path naar echte foto
} // end else
echo "<table border='0' cellpadding='0' cellspacing='2'><tr><td ><b>" . $pathspatie . "</b> <small>(" . $count . ")</small>
<br><br><center><small>Pictures " . ($begin + 1) . " - " . $eind . "</small></center></td></tr></table>";
if(($begin - $aantalFotos) >= 0){
$navigation = "<a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin - $aantalFotos) . "'><</a> " . $navigation;
} // end if
if(($begin + $aantalFotos) < $count){
$navigation .= " <a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin + $aantalFotos) . "'>></a>";
} // end if
echo $navigation . "<br><br>";
echo "</td></tr><tr>";
$fotonr = 1;
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){ // error occurres here.
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
} // end for
If anyone can see what the problem is it would be great!
I did not understand you exact goal but maybe it is better to write one more check:
if(!isset($reacties[$i]) || $reacties[$i]==0){
echo "0";
}

Wrong calendar displaying after server crash

Few days ago server crashed and was down for few hours, after server become available, my calendar started to display wrong data. It had to show me current month and 5 next(half a year in total). Server data is correct. Any ideas whats wrong with calendar? Does mysql server time can make my calendar show wrong data?
if (!isset($_MONTH))
$_MONTH = 6;
if (isset($_POST['subscribe_month']))
$_MONTH = $class->_dig($_POST['subscribe_month']);
$sql = mysql_query("SELECT d.header, d.id FROM " . $class->_cfg['pfx'] . "workshops as w
LEFT JOIN " . $class->_cfg['pfx'] . "workshops_date as wd ON wd.cid=w.id
LEFT JOIN " . $class->_cfg['pfx'] . "dictionary as d ON d.id=wd.city
WHERE w.public='1' and wd.public='1' and wd.date_end>='" . date("Y-m-d") . "' a
nd wd.predprosomtr='0' " . $where . " ORDER BY d.rang");
$CityList = array();
while ($_sql = mysql_fetch_assoc($sql)) {
$CityList[$_sql['id']] = $_sql['header'];
}
if ($Fcity && $Fcity != 0)
$where.=" and d.id=" . $Fcity . "";
elseif ($_POST['city'] && $class->_dig($_POST['city']) > 0)
$where.=" and d.id=" . $class->_dig($_POST['city']) . "";
if ($CitySearch != 0)
$where.=" and wd.city=" . $CitySearch . " ";
$sql = mysql_query("SELECT w.header, w.direction, w.subheader, wd.colsmonth, wd.is_new, wd.public_date_finish, wd.p_date_finish, w.aliaslink, wd.aliaslink as wd_aliaslink, w.direction, wd.city, wd.date_start, d.header as city_name, wd.date_end, wd.cid, wd.id as wd_id, w.id as w_id FROM " . $class->_cfg['pfx'] . "workshops as w
LEFT JOIN " . $class->_cfg['pfx'] . "workshops_date as wd ON wd.cid=w.id
LEFT JOIN " . $class->_cfg['pfx'] . "dictionary as d ON d.id=wd.city
WHERE w.public='1' and wd.public='1' and wd.date_end>='" . date("Y-m-d") . "' and w.direction<>'' and wd.predprosomtr='0' " . $where . " ORDER BY wd.date_start, wd.city");
//$output.=$where;
$month = 12;
$year = date("Y");
while ($_sql = mysql_fetch_assoc($sql)) {
$view = true;
if ($_sql['public_date_finish'] == '1' && $_sql['p_date_finish'] < date("Y-m-d"))
$view = false;
if ($view) {
$arWorkshops[$_sql['w_id']] = $_sql;
if (!isset($arWorkshopsCity[$_sql['cid']][$_sql['city']]) && $_sql['city'] > 0)
$arWorkshopsCity[$_sql['cid']][$_sql['city']] = $_sql['city'];
if (isset($arWorkshopsDate[$_sql['cid']]['count']))
$arWorkshopsDate[$_sql['cid']]['count'] = $arWorkshopsDate[$_sql['cid']]['count'] + 1;
else
$arWorkshopsDate[$_sql['cid']]['count'] = 1;
$direct = explode('#', $_sql['direction']);
for ($i = 0; $i < count($direct); $i++) {
if (trim($direct[$i]) != '') {
$arDirectionList[$direct[$i]] = $direct[$i];
}
}
//$arDirectionList[$_sql['direction']]=$_sql['direction'];
if (!isset($arWorkshopsDate[$_sql['cid']][ceil($class->convert_date($_sql['date_start'], '.', "month"))]))
$arWorkshopsDate[$_sql['cid']][ceil($class->convert_date($_sql['date_start'], '.', "month"))] = $_sql;
if ($class->convert_date($_sql['date_start'], '.', "month") < $month && $class->convert_date($_sql['date_start'], '.', "year") == $year) {
$month = $class->convert_date($_sql['date_start'], '.', "month");
$year = $class->convert_date($_sql['date_start'], '.', "year");
}
//if($class->convert_date($_sql['date_start'], '.', "year")==(date("Y")+1))$year=$class->convert_date($_sql['date_start'], '.', "year");
//$output.=$_sql['header']."-".$_sql['date_start']."-".$_sql['wd_id']."<br>";
}
}
//var_dump($arWorkshopsDate[185]);
$output.='<table class="table"><tr><th width="60"> </th><th class="first" style="width:auto">Название</th>';
if ($_MONTH == 12)
$w = "5%"; else
$w = "9%";
for ($i = $month; $i < ($month + $_MONTH); $i++) {
if ($year == date("Y"))
$m = $i;else
$m++;
if ($m <= 12 && $year == date("Y")) {
$output.='<th class="month" style="width:' . $w . '">' . $class->convert_date($m, '.', "myear") . ' <span>' . $year . '</span></th>';
} else {
if ($m > 12) {
$m = 1;
$year = $year + 1;
}
$output.='<th class="month" style="width:' . $w . '">' . $class->convert_date($m, '.', "myear") . ' <span>' . $year . '</span></th>';
}
}
$output.=' <th style="width:10%">';
if ($typeblock == 'webinars')
$output.='Формат';
else
$output.='Город';
$output.='</th></tr>';
if (isset($arWorkshops)) {
//foreach($arWorkshops as $LO=>$listOrd){
foreach ($arWorkshops as $k => $value) {
if (!$direction || $direction == 0)
$direction2 = $class->_direction($value['direction']);
else
$direction2 = $direction;
foreach ($arWorkshopsCity[$k] as $LO => $listOrd) {
$output2 = "";
$link_date = "";
$pt = 0;
$m_nth = ceil($month);
$is_new_class = '';
for ($i = ceil($month); $i < ($month + $_MONTH); $i++) {
if ($m_nth > 12)
$m_nth = 1;
if (isset($arWorkshopsDate[$k][$m_nth]) && $arWorkshopsDate[$k][$m_nth]['city'] == $LO) {
$pt++;
if ($pt == 1)
$city_name = $arWorkshopsDate[$k][$m_nth]['city_name'];
//if(isset($_TYPE) && $_TYPE!=0)$output.='<td class="date"><a href="/'.$typeblock.'/'.$value['aliaslink'].'/'.$arWorkshopsDate[$k][$i]['wd_aliaslink'].'/">';
//else
if (($arWorkshopsDate[$k][$m_nth]['is_new'] == '1') || ($arWorkshopsDate[$k][$m_nth + 1]['is_new'] == '1')) {
$is_new_class = " it_is_new";
} else {
$is_new_class = '';
}
$output2.='<td class="date"><a href="/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/' . $arWorkshopsDate[$k][$m_nth]['wd_aliaslink'] . '/">';
$link_date = '/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/' . $arWorkshopsDate[$k][$m_nth]['wd_aliaslink'] . '/';
if ($arWorkshopsDate[$k][$m_nth]['colsmonth'] > 0)
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "</a><br />" . $arWorkshopsDate[$k][$m_nth]['colsmonth'] . " мес.";
elseif ($arWorkshopsDate[$k][$m_nth]['date_start'] == $arWorkshopsDate[$k][$m_nth]['date_end'])
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "</a>";
else
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "<br />-" . $class->convert_date($arWorkshopsDate[$k][$m_nth]['date_end'], '.', "day_month") . "</a>";
$output2.='</td>';
}else {
$output2.='<td></td>';
}
$m_nth++;
}
if (($arWorkshopsDate[$k][$m_nth]['is_new'] == '1')) {
$is_new_class = " it_is_new";
}
$output.='<tr><td class="' . $is_new_class . '"> </td><td>';
//if(isset($_TYPE) && $_TYPE!=0)$output.='<strong>'.$value['header'].'</strong>';
//else
if ($pt == 1 && $arWorkshopsDate[$k]['count'] == 1)
$link = $link_date;
else
$link = '/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/';
$output.='<a href="' . $link . '"><strong>' . $value['header'] . '</strong>';
if (trim($value['subheader']) != '')
$output.=': ' . $value['subheader'] . '';
$output.='</a>';
$output.='</td>';
$output.=$output2;
$output.=' <td class="city">' . $city_name . '</td></tr>';
}
}
//}
}
$output.='</table>';
?>
Issue solved. By default some "good" coder made it show only from 12th month in $month = 12;
I just changed it to $month = date("m"); And this solved my issue

How can I limit the total number of SimpleXML results?

I'm looking to limit to the first 5 results returned here.
This works, but it does not limit the data set:
<?php
foreach($sxml->status as $status){
$name = $status->user->name;
$image =$status->user->profile_image_url;
$update =$status->text;
$url = "http://twitter.com/" .$status->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
I've tried this:
<?php
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
and am really kind of unsure why it doesn't work. If I simply do:
<?php echo $sxml->status[0]->user->name ?>
then I get the proper result. But when attempting it within the for loop, I get NULL.
Perhaps some kind of while? A different setup altogether? Thanks so much for any help you can give on this.
Change this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
To this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->status[$n]->user->name;
$image = $sxml->status[$n]->user->profile_image_url;
$update = $sxml->status[$n]->text;
$url = "http://twitter.com/" . $sxml->status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
You accidentally were writing this:
<?php echo $sxml->$status[0]->user->name ?>
Where it was trying to us $status[0] as a variable variable and of course, that doesn't exist and is thus undefined/null.
If you had something that works, why overcomplicate things by changing everything? Just limit the processing to the first N entries.
$i = 0;
foreach ($sxml->status as $status) {
if (++$i > 5) {
// stop after 5 loops
break;
}
// the rest is identical
}
Btw, $n = 0; $n <= 5; $n++ will limit to the first 6 entries, not 5.
$n = 0; $n < 5; $n++ will do what you asked for.
Don't you mean
$n = 0; $n < 4; $n++
I've also tried this, and it works great :-)
foreach ($xml->item as $item) {
if (++$i > 5) { break; }
$item->title . '';
} //foreach()
Note I'm not using $i = 0; it seems to know that by default ;-)
I hope this helps some one.

Categories