Welcome to WebmasterWorld Guest from 50.16.24.12

Forum Moderators: coopster & jatar k

(help) Show content only if.

Show content if number of entries is more than x-number

   
8:16 pm on May 24, 2012 (gmt 0)



Hello, I have a question if someone can help, I would appreciate it very much.

I would like to show content or echo a line of text, but only if the amount of entries equal 5 or more, for example in my data file.

Example data file content which is semi-colon seperated, if it makes a difference:

entry1;
entry2;
entry3;
entry4;


Code I came up with, but I know it won't work...

$file = "./data_file.txt";

if
{
$lines = count(file($file));
}

echo "Sorry, there are only $lines entries. 5 entries are needed to show the content below.";

else
{

echo "Hurray, there is $lines entries. Content is available to view.";

}

Something to that affect. Either with a "less than" or "not equal" statement.

Thank you.
8:50 pm on May 24, 2012 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



You know it won't? It should. :-) You probably have a path problem. This works if it's in the same directory.

<?php
$count = count(file('fivelines.txt'));
echo "Line count: $count";
?>

But what you should do is 1) use the full server path to the file, especially if it exists in some other directory, and 2) check for it's existence.


<?php
$myfile = $_SERVER['DOCUMENT_ROOT'] . '/some-directory/fivelines.txt';
if (! is_file($myfile)) { echo "$myfile doesn't exist"; }
else {
$count = count(file($myfile));
echo "Line count: $count";
}
?>


So if you want a conditional,


<?php
$myfile = $_SERVER['DOCUMENT_ROOT'] . '/some-directory/fivelines.txt';
if (! is_file($myfile)) { echo "$myfile doesn't exist"; }
else {
$count = count(file($myfile));
if ($count >= 5) { echo "Line count: $count"; }
else { echo "Didn't make the grade. Less than 5."; }
}
?>
9:11 pm on May 24, 2012 (gmt 0)



Thanks Rocknbil, your code(s) worked really well! I wasn't far off. Cheers, much appreciated! :)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month