Hi guys
Is there a way I can see how many liones are in a variable
Example
$names'chris
dave
fred';
How could I make this return
3
Thanks in advance
Hi guys
Is there a way I can see how many liones are in a variable
Example
$names'chris
dave
fred';
How could I make this return
3
Thanks in advance
If you’re storing multiple items in a string like that, use an array.
$names = array("Chris", "Dave", "Fred");
echo count($names); // returns 3
Unfortunately it is a textarea where they enter 1 name per line
Is there a way i can get the amount of lines this way?
explode on "
". (Note: You must use double quotes.)
Try giving this a shot:
$_POST["Textarea"] = nl2br($_POST["Textarea"]);
$lines = explode("<br />", $_POST["Textarea"]);
echo count($lines);
$var = "one
two
three";
// PHP_EOL = OS independent* means of indentifying an End Of Line
$bits = explode( PHP_EOL, $var);
var_dump( $bits );
//or
echo count($bits);
Learn something new every day. PHP_EOL is a defined constant for all versions of PHP > 4.3 and 5.0.2 as part of the PHP Core.
The only potential problem with the above examples is that they will count empty lines as well - maybe that’s desired behaviour, I don’t know.
If you wanted to ignore all empty (or whitespace) lines you could do something like:
$names = '
chris
dave
fred
';
$namesArray = preg_split('#'.PHP_EOL.'#', $names, -1, PREG_SPLIT_NO_EMPTY);
$numNames = count($namesArray);
PREG_SPLIT_NO_EMPTY
That’s so cool, I keep forgetting about that switch.