Karuppiah RK
Karuppiah RK

Reputation: 3964

find a string in an array with splited variable letters

$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?

Upvotes: 0

Views: 46

Answers (3)

Steven
Steven

Reputation: 1

<?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;
       }
}
?>

Upvotes: 0

hlscalon
hlscalon

Reputation: 7552

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/>";

Upvotes: 1

Mike
Mike

Reputation: 24423

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"
}

Upvotes: 1

Related Questions