I want my page to display a button for “next” and “previous” paragraph, on the condition that there is a “next” or “previous” paragraph.
Here’s what I have so far. I start from the paragraph id that I know and I look for the preceding and following paragraph, which I load into separate variables.
Then I check to make sure a preceding or next paragraph exists. I then tell the computer to show the link, only if the paragraph exists.
Currently everything is working except for the test for $nextPid. The test for $prevPid works fine. When I am at the first paragraph no link for for ‘previous paragraph’ shows up, but when I am at the last paragraph in the file a link for ‘new paragraph’ still shows up.
Any ideas what I could be doing wrong?
$xmldoc = simplexml_load_file('/tmp/lecture.xml');
$prevPid = $xmldoc->xpath("//p[@id='$refPid']/preceding::p[1]/@id");
$nextPid = $xmldoc->xpath("//p[@id='$refPid']/following::p[1]/@id");
if (sizeof($nextPid) > 0)
{
echo "<a id=\"adjParNxt_$nextPid[0]\" class='adjPara' data-refPid=\"$refPid\" data- adjPid=\"$nextPid[0]\" data-refFs=\"$refFs\">Next Paragraph</a> ";
}
if (sizeof($prevPid) > 0)
{
echo "<a class='adjPara' data-refPid=\"$refPid\" data-adjPid=\"$prevPid[0]\" data- refFs=\"$refFs\">Previous Paragraph</a>";
}
The data I’m working with can be found here http://jeffreycwitt.com/xml_data.xml
Your code is trying to do the right thing, but bumping into a minor issue. In old versions* of PHP,
SimpleXMLElement::xpath()would wrongly returnFALSEin some edge cases. In more recent, fixed, versions it returns an empty array.The PHP version that you’re running the code on must be one which is returning
FALSE. The problem is thatsizeof(FALSE)is1, meaning that your condition is always true.What to do?
Well, my first piece of advice is to upgrade PHP to something more recent!
If you really must keep the old version of PHP, then you can change the
ifstatements to be like the following, which will continue to work if/when you do upgrade.Notes
sizeof(FALSE)returns1, read thecount() manual page.