0

I have this array

array(6) {
  [0]=>
  string(7) "1234567"
  [1]=>
  string(5) "7548#"
  [2]=>
  string(9) "1254#abc#"
  [3]=>
  string(5) "32514"
  [4]=>
  string(6) "2548##"
  [5]=>
  string(5) "3258#"
}

I want to validate this data based on provided condition.

If ID(array[0] and array[3] or array[n]) is an integer check the *data* which is(array[1] and array[4] or array[n]) and if that data not contain more then one #, return false;

here is my sample code, but I'm only able to check the first and 2nd array,

if(preg_match('/^[1-7]{1,7}$/', current($arr))){
  next($arr);  
  if(substr_count(next($arr),"#") <=1)
     //false
  else
    echo "true";  
}

help needed, thanks.

1
  • Your question is not clear... Commented Dec 22, 2017 at 8:32

2 Answers 2

2

You can use a for loop, which allows you to control the start point, the condition when to stop and the step your using, so...

$arr = ["1234567", "7548#", "1254#abc#", "32514", "2548##", "3258#"];
for ( $i = 0; $i < count($arr); $i+=3)  {
    echo $arr[$i].PHP_EOL;
    if ( preg_match('/^[1-7]{1,7}$/', $arr[$i]) ) {
        if(substr_count($arr[$i+1],"#") > 1)    {    // Check if it's +1 or +2 here
            echo "true".PHP_EOL;
        }
        else    {
            echo "false".PHP_EOL;
        }
    }
}

This loops from the start to the number of elements in your source, but just every 3rd item. The rest uses similar code to what you've already got, but using the array elements relative to the loop counter ($arr[$i+1] for example). You will have to check if this is the right element you want to check as it may be $arr[$i+2], but the concept is the same.

This outputs..

1234567
false
32514
true

One thing I would recommend is to try and write if statements so that you always get something from it being 'true'. In your code you use <=1 and then there is nothing to do - if you change that round to >1, then it means you can get rid of the 'empty' statement.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks a a lot nigel, by the way, how can I do that also using javascript.??
Javascript would be virtually the same, for loops like this are common in most languages.
2

you need to create a loop then you can write your rules for specific n.

$n = 3; //Your modulo
for($x = 0, $l = count($array); $x < $l; $x++ ) { //$array is your array
   if($x % $n == 0) {
       $result = preg_match('/^[1-7]{1,7}$/',$array[$x]);
   } else if ($x % $n == 1) {
       $result = substr_count($array[$x], '#') > 1;
   } else {
       $result = true; //no specific rule
   }

   if(!$result) { //if validation fails
      echo "Validation failed";
      break;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.