Separate a String and check if the string is the key of array in php

时间:2018-02-03 10:54:16

标签: php arrays string key

I am trying to separate them all according to white space.

$string = "1 2 3 10 12";

According to this string, I want to separate like that.

$a = "1";
$b = "2";
$c = "3";
$d = "10";
$e = "12";

After that, I would like to check those strings are included as the key of an array. Here is my array,

$data = [
"1" => "Book",
"2" => "Paper",
"3" => "Pencil",
"10" => "Eraser",
"11" => "Ruler",
];

So, How can I separate an array and store the parts in each variable? And How to check those variable are included in array as a key? Sorry for my English :D. Thanks.

3 个答案:

答案 0 :(得分:2)

Use the explode function to seperate the values and then check if the array key exists using array key exists.

$stringArray = explode(" ",$string);

foreach($stringArray as $stringPeice){
   if(array_key_exists($stringPeice, $data)){
     //do something
   }
}

答案 1 :(得分:2)

You can use explode to create an array of keys and then use array_diff to get an array of keys that are not in the $data:

$string = "1 2 3 10 12";

$keys = explode(' ', $string);

$data = [
    "1" => "Book",
    "2" => "Paper",
    "3" => "Pencil",
    "10" => "Eraser",
    "11" => "Ruler",
];

$diff = array_diff($keys, array_keys($data));

Here is the demo.

答案 2 :(得分:0)

If you want to get the entries from $data whose key exists in $string, you can use array_intersect_key(), and array_fill_keys() to create an array containing keys from the result of exploding $string:

$o = array_intersect_key($data, array_fill_keys(explode(" ", $string), ""));

Here's a demo