marcnyc
marcnyc

Reputation: 585

how to find a value contained inside a value inside an array?

If I have the array:

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

I know that in_array() is what to use if I want to find "Mac" inside $os.

But what I have the array:

$os = array( [1] => "Mac/OSX", [2] => "PC/Windows" );

and I want to see if "Mac" is contained in $os?

Upvotes: 4

Views: 77

Answers (7)

user3201528
user3201528

Reputation:

 function FindString($string, $os)
 {
    // put the string in between // 
    $preg = "/$string/";

    // Match found 
    $found = false;

    // loop each value 
    for($j = 0; $j < count($os); $j++)
    {
        // check with pattern 
        if(preg_match($preg,$os[$j]))
        {
            // set var to ture 
            $found = true;

            // Break 
            break;
        }
    }

    if($found == false)
    {
        die("Unable to found the string $string.");
    }

    echo "String $string found in array index $j and value is $os[$j]";

 }

 $where =array("Mac/OSX","PC/Windows" );
 $what = "Mac";
 FindString($what, $where);

Upvotes: 0

Hirdesh Vishwdewa
Hirdesh Vishwdewa

Reputation: 2362

You can try this-

$os = array( "Mac/OSX", "PC/Windows" );    
function findInArray($os){
 foreach($os as $val){
  if(strpos($val, $word_to_search) !== false){
   return true;
  }
 }
 return false;
}

Upvotes: 1

Peter
Peter

Reputation: 9123

You could also use array_map to do this. Take a look at the following code:

$array = array(
    'Mac/OSX',
    'PC/Windows',
);



$result = in_array(true, array_map(function ($word, $match, $char = "/") {
    $words = explode('/', $word);
    return in_array($match, $words) ? true : false;
}, $array, array('Mac')));

var_dump($result); // bool(true) 

Upvotes: 1

Saty
Saty

Reputation: 22532

By using foreach and strpos

$os =array("Mac/OSX","PC/Windows" );
$string = "Mac";
foreach ($os as $data) {
   //echo $data;
    if (strpos($data,$string ) !== FALSE) { 
        echo "Match found"; 
    }else{
        echo "not found";
    }
}

DEMO

Upvotes: 0

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can simply use preg_grep function of PHP like as

$os = array( '1' => "Mac/OSX", '2' => "PC/Windows" );

print_R(preg_grep("/Mac/",$os));

Output:

Array ( [1] => Mac/OSX ) 

Upvotes: 0

Ali
Ali

Reputation: 1438

Here is another solution:

array_map(function($v){
    if (strpos($v, 'Mac') !== false) {
    echo 'found';
    exit;
}
},$os);

echo "Not found";

DEMO

Upvotes: 0

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

Try:

$example = array("Mac/OSX","PC/Windows" );
$searchword = 'Mac';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });

Upvotes: 2

Related Questions