0
$states = "Mississippi Alabama Texas Massachusetts Kansas";
$statesA = explode(' ',$states);
$statesArray = array();

foreach($statesA as $state) {
if(preg_match( '/xas$/', trim($state)))
$statesArray[0] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/^k.*s$/i', trim($state)))
$statesArray[1] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/^M.*s$/', trim($state)))
$statesArray[2] = trim($state);
}

foreach($statesA as $state) {
if(preg_match('/a$/', trim($state)))
$statesArray[3] = trim($state);
}

foreach($statesA as $state) { #PROBLEM HERE
if(preg_match('/^M/', trim($state)))
$statesArray[4] = trim($state);
}

foreach ( $statesArray as $element => $value )
print( "Element $element of the Array is $value <br />");

The task is to basically to output a word that begins with the letter M in the variable state. I have "Mississippi Alabama Texas Massachusetts Kansas" in $states. When I try to print it out, Massachusetts gets printed out rather than Mississippi. Why is that?

1
  • Well, Massachusetts is the last element to match, overwriting the previous match of Mississippi. Commented Mar 24, 2014 at 10:39

1 Answer 1

2
<?
 foreach($statesA as $state) { #PROBLEM HERE
  if(preg_match('/^M/', trim($state)))
  $statesArray[4] = trim($state);
  }
?>

In your code above, both Massachusetts and Mississippi match your expression, and they are both stored in $statesArray[4]. If you want only the first match, maybe you should also check if $statesArray[4] is already set. So, something like this should work:

<?
  foreach($statesA as $state) { #PROBLEM HERE
    if(preg_match('/^M/', trim($state)) && !isset($statesArray[4]))
    $statesArray[4] = trim($state);
  }
?>

This would fill $statesArray[4] only if it is not already set.

Let me know if this works for you.

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

7 Comments

That wouldn't actually accomplish anything.
Could you please clarify what you mean?
That particular expression /^M.*s$/ is to search for a word that begins with M and ends with S hence, Massachusetts. It shouldn't match Mississippi since it does not end with S. The purpose for the last for each is to be able to print out the first word that begins with M which is Mississippi in this case. Is the syntax wrong? Thank you for helping!
Oh yeah, sorry I did not have a proper look. However the solution is the same. I'll edit my answer.
@Shinji: Missisippi and Massachusetts both begin with M. They're both matched by your expression and one is overwritten by the other.
|

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.