Check for correct number of elements in exploded string Let's say I've got this string:

$str = '1-2-3';


and I explode this like so:

$strSplit = explode('-', $str);


what would be the best way to check if I've got the correct number of elements and whether they are numeric (because the input can vary)?

Straightforward, I would say something like this:

if (isset($strSplit[0]) &amp;&amp; is_numeric($strSplit[0]) &amp;&amp; isset($strSplit[1]) &amp;&amp; is_numeric($strSplit[1]) &amp;&amp; isset($strSplit[2]) &amp;&amp; is_numeric($strSplit[2]) {
    // some code
}


But you could also do:

if (count($strSplit) === 3 &amp;&amp; is_numeric($strSplit[0]) &amp;&amp; is_numeric($strSplit[1]) &amp;&amp; is_numeric($strSplit[2])) {
    // some code
}


You can use some array functions to check for the is_numeric part, but that seems fussy, less readable and is probably slower. I could be wrong, though...
There are several options.

My favorite (based on readablity and simplicity) is using array_filter to remove everything that is not a number from the array and then comparing with the original to see if anything changed, then using count to make sure you have the correct number of elements:

$str = '1-foo-3';
$strSplit = explode('-', $str);

if(count($strSplit) == 3 &amp;&amp; $strSplit == array_filter($strSplit, 'is_numeric')){
    // array is numeric // run code
} else {
    // array is non-numeric
}




Edit: did some speed testing and tried a few more options and validations.

I speedtested with the following inputs:

A: $strSplit = explode('-', '1-2-3');//3 elements, all numeric //evaluates true
B: $strSplit = explode('-', '1-foo-3-4');//4 elements, not all numeric //evaluates false


The results (after 1 million cycles) were as follows :

Static isset and is_numeric :

if (isset($strSplit[0]) &amp;&amp; is_numeric($strSplit[0]) &amp;&amp; isset($strSplit[1]) &amp;&amp; is_numeric($strSplit[1]) &amp;&amp; isset($strSplit[2]) &amp;&amp; is_numeric($strSplit[2]) &amp;&amp; !isset($strSplit[3])) {
    // some code
    // A : speed 0.68 mircoseconds
    // B : speed 0.48 mircoseconds
}


Looped isset and is_numeric :

for($i=0; $i&lt;3;$i++) if(!isset($strSplit[$i]) || !is_numeric($strSplit[$i])) $nonNumeric = true;

if(!isset($strSplit[($i+1)]) &amp;&amp; !isset($nonNumeric)){
    // some code
    // A : speed 0.96 mircoseconds
    // B : speed 1.00 mircoseconds
}


count and array_filter :

if(count($strSplit) == 3 &amp;&amp; $strSplit == array_filter($strSplit, 'is_numeric')){
    // some code
    // A : speed 2.00 mircoseconds
    // B : speed 0.16 mircoseconds
}