0
$string = 'Ma';

$arr1 = str_split($string);

foreach($arr1 as $a)
{
    echo $a."<br>";
}

$os = array("Mac", "NT", "Irix", "Linux", "apple");

Here I have some strings in $string variable. In this line echo $a."<br>"; it returns this result

M
a

it splits the string. Now I want to find the words (array("Mac", "NT", "Irix", "Linux", "apple");) with these splited string (M a). For example, My string is Ma, First I want to find the string in an array which string starting with M and next I want to find another string in an array which string with a. Then I want to echo those both strings. Results should be Mac apple. How do I get it?

1
  • foreach($arr as $item) { if (substr($item, 0, 1) == 'M') { found_it(); }} Commented Sep 25, 2014 at 17:02

3 Answers 3

1

Just loop the array and compare the first letter of the strings.

$string = 'Ma';
$arr1 = str_split($string);
$os = array("Mac", "NT", "Irix", "Linux", "apple");

foreach($arr1 as $a)
{
    foreach ($os as $o)
    {
       if ($o[0] === $a) 
           echo $o, "<br/>"; // Mac<br/>apple<br/>
    }
}

Or, with a different approach:

$string = 'Ma';
$arr1 = str_split($string);
$os = array("Mac", "NT", "Irix", "Linux", "apple");

foreach ($os as $o)
    if(in_array($o[0], $arr1))
       echo $o, "<br/>";
Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like this:

$string = 'Ma';
$oses = array("Mac", "NT", "Irix", "Linux", "apple");

foreach (str_split($string) as $first_letter) {
    $fl_array = preg_grep("/^".$first_letter."/", $oses);

    var_dump($fl_array);
}

Output:

array(1) {
  [0]=>
  string(3) "Mac"
}
array(1) {
  [4]=>
  string(5) "apple"
}

Comments

0
<?php


    $arr=array("Mac",'apple',"linux");

      foreach($arr as $v){

          if(preg_match("/^M/",$v)){

           echo $v."\n";
      }

       if(preg_match("/^a/",$v)){

           echo $v;
       }
}
?>

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.