-1

I have the following code that uses regular expression to do some matching and I think should be working. But I am getting an undefined offset error which I can't fix. Can I have some help understanding why and how to fix the issue? I think the issue might have to with the $match but i'm not sure.

$states = "Mississippi Alabama Texas Massachusetts Kansas"; 
$statesArray = array();


if(preg_match( '/xas$/', $states,$match )){
 $statesArray[0] = $match[ 1 ];
}


if(preg_match('/^k.*s$/i', $states,$match )){
 $statesArray[1] = $match[ 1 ];
}


if(preg_match('/^M.*s$/', $states,$match )){
  $statesArray[2] = $match[ 1 ];
}

if(preg_match('/a$/', $states,$match )){
 $statesArray[3] = $match[ 1 ];
}

if(preg_match('/^M/', $states,$match )){
 $statesArray[4] = $match[ 1 ];
}



foreach ( $statesArray as $element => $value )
   print( "$value <br />");
Nubbins
  • 49
  • 3

1 Answers1

0

You code is working fine under php 7.0, but I think you'd better write such code like this below for better maintainability:

<?php
$states = "Mississippi Alabama Texas Massachusetts Kansas"; 
$statesArray = array();

$i=0;
if(preg_match( '/xas$/', $states,$match )){ 
     $statesArray[$i++] = $match[ 0 ];
}


if(preg_match('/^k.*s$/i', $states,$match )){ 
     $statesArray[$i++] = $match[ 0 ];
}


if(preg_match('/^M.*s$/', $states,$match )){ 
      $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/a$/', $states,$match )){ 
     $statesArray[$i++] = $match[ 0 ];
}

if(preg_match('/^M/', $states,$match )){ 
     $statesArray[$i++] = $match[ 0 ];
}



foreach ( $statesArray as $element => $value )
       print( "$value <br />");
Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57