A
A
Alexander_Mas2019-03-24 09:47:37
PHP
Alexander_Mas, 2019-03-24 09:47:37

Check if a string is in an array?

It is not equal to the value of the array cell, but whether it is included as part of the value.
$owned_urls= array('This is a first site website1.com', 'This is a 2 site website2.com', 'Third site website3.com');
$string = 'website3.com';
We need to check if there is a cell in the array containing $string. What is the easiest option?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly, 2019-03-24
@Alexander_Mas

If you need to find out the number of the cell that contains the search string:

$i = -1;
foreach ($owned_urls as $k => $v) {
  $pos = strpos($v, $string);
  if ($pos > 0) $i = $k;
}

if ($i > 0) {
  //значение найдено в ячейке, номер которой содержится в $i
} else {
  //значение не найдено
}

If not needed:
$str = implode(",", $owned_urls);
$pos = strpos($str, $string);

if ($pos > 0) {
  //значение найдено
} else {
  //значение не найдено
}

G
George, 2019-03-24
@zhora_pro

key(array_filter($owned_urls, function ($item) use ($string) {
    return mb_strpos($item, $string);
}));

Returns the number of the first cell containing a string or NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question