Reputation: 9
PHP Code
$testcases1 = explode(" ",$_POST['testcases']);
$num1 = $testcases1[0];
$num2 = $testcases1[1];
echo "count-"count($testcases1);
echo "num2-"$num2;
Correct
i/p : 3 2 o/p : count-2 num2-2
My Issue
i/p : 3(just a single space) o/p : count-2 num2-
and $num2 is behaving as it has the value 0 what can i do for this ...
num2 can be 0 to 100... how do i acheive this
Upvotes: 0
Views: 56
Reputation: 627
You can use rtrim()
to remove the spaces http://php.net/rtrim
$testcases1 = explode(" ",$_POST['testcases']);
$num1 = rtrim($testcases1[0], ' ');
$num2 = rtrim($testcases1[1], ' ');
echo "count-"count($testcases1);
echo "num2-"$num2;
If multiple spaces between the 2 numbers
$testcases1 = array_keys(array_filter(explode(' ', $_POST['testcases'])));
$num1 = rtrim($testcases1[0], ' ');
$num2 = rtrim($testcases1[1], ' ');
echo "count-"count($testcases1);
echo "num2-"$num2;
Upvotes: 1
Reputation: 91744
It looks that there is more than 1 space between the numbers and that causes spaces to become part of your result array.
In that case you are better off using preg_split()
as that can split on a regular expression:
$testcases1 = preg_split('/\s+/',$_POST['testcases']);
This will explode the string on 1 or more white-space characters (\s
): Spaces, tabs or new-lines.
If you just want to explode on 1 or more spaces (no tabs or new-lines), you can use:
$testcases1 = preg_split('/[ ]+/',$_POST['testcases']);
On the other hand, if you need 2 inputs, you are probably better off using 2 input fields as that will avoid these kinds of parsing problems.
Upvotes: 0
Reputation: 4297
I think the issue is that your $_POST['testcases']
contain a trailing white space.
You should trim $_POST['testcases']
, so that it explodes correctly. Alter your first line to:
$testcases1 = explode(" ",trim($_POST['testcases']));
Upvotes: 1