简体   繁体   中英

checking if a value is present in an array

I am trying to compare a string with an array to see if the string is present in the array and if so echo 'in array'. I keep only being able to have the echo work as I want with the very last entry in the array.

foreach($array as $key => $value) {
    foreach($entries as $entry) {
        if($entry == $value) echo 'in array 1';
    }
    if (in_array($value, $entries)) {
        echo 'in array 2';
    }
    if(isset($entries[$value])) {
        echo 'in array 3';
    }
}

the echo for 'in array 1' and 'in array 2' work only on whatever the very last entry in the $entries array is, and the echo for 'in array 3' doesnt work at all.

Its probably something stupid but I am not seeing it...

edit:

here is some examples of the arrays

$entries =
array(5) {
  [0]=>
  string(14) "example text 1"
  [1]=>
  string(14) "example text 2"
  [2]=>
  string(14) "example text 3"
  [3]=>
  string(14) "example text 4"
  [4]=>
  string(14) "example text 5"
}

$array = 
array(5) {
  [0]=>
  string(14) "example text 1"
  [1]=>
  string(14) "example text 2"
  [2]=>
  string(14) "example text 3"
  [3]=>
  string(14) "example text 7"
  [4]=>
  string(14) "example text 8"
}

so now when I do

foreach($array as $key => $value)

$value should have the values from my $array and I need to compare each one of those values to see if they are present in my $entries array. If so id like to echo 'in array'

edit 2:

if it makes a difference my $entries array is being created by file() since the information is coming from a log. Everytime a new file is added, it is logged, then i want to compare incoming files to the log, determine if they have been added already, and if not, add them.

Your code seems to just check what is in common in two arrays, and does it three different ways. The reason one will work over another depends on the data. The there comparators == , in_array and isset work differently. Really need to see your array structure / sample data to comment further.

However, what you're currently doing, finding common elements of two arrays, can easily be done with array_diff() or array_intersect()

Your very first line -

I am trying to compare a string with an array to see if the string is present in the array and if so echo 'in array'.

can just be achieved with just one call to in_array , like in_array('cat', array('cat', 'dog', 'mouse'));

$value is not a key.

Value is a "value".

if you really wanted to do what you are doing you could do:

if(isset(array_flip($entries)[$value])) {
    echo 'in array 3';
}

But it might not work if you have several elements with the same value.

See DOCs

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