简体   繁体   中英

php check if value exists in associative array

I have array such below:

$import_emails = [];

$import_emails[]=[
    'to'=>$to,
    'from'=>$from,
     'cc'=>$cc,
     'subject'=>$subject,
    'text'=>$text,
    'date'=> date('Y-m-d H:i:s',strtotime($date))
];

Example array data:

Array
     (
    [0] => Array
    (
        [to] => nastya.gorobets95@gmail.com
        [from] => babboe1 babboe1 <test.babboe1@gmail.com>
        [cc] => 
        [subject] => Test Subject
        [text] => Test content.
        Please, write me later
        Thanks!

        [date] => 2017-06-29 18:04:53
    )

[1] => Array
    (
        [to] => Anastasia Gorobets <nastya.gorobets95@gmail.com>
        [from] => babboe1 babboe1 <test.babboe1@gmail.com>
        [cc] => babboesignal@edu-crm.com
        [subject] => Tema
        [text] => Bla bla bla
         Test email! :)

        [date] => 2017-07-02 11:55:50
    )

 )

How can I check if value, for example 'nastya' exists in arrays item ['to'] ? Maybe there is some function for it? Thanks!

Sometimes I convert the associative array to a flat array using array_column . Then check if it exists.

$dataSubjectsValue = array_column($data, 'subject');
if (in_array('Test Subject', $dataSubjectsValue)) {
  // ...do your stuff
}

I think this is a little more readable than using foreach loops.

You need foreach your array.

foreach ($import_emails as $key => $value) {

$to = $value['to'];

if($to == "nastya") {
echo 'Found!';
break;
}

}

You want to check if your value present in that array value.
( you want to find "nastya" in to field of array)

if( isset( $import_emails[$incex_of_array]['to']) )
    if(strpos($import_emails[]['to'], 'youvalue'))
        // you action 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM