0

I need to make a loop that checks if an array ( $array ), contains a string ( 'thisisaverylongstring' ), that contains another string ( 'isavery' ).

How would I write this in valid PHP?

5
  • Did you tried in_array() and array_search() functions ? Commented Mar 19, 2012 at 17:00
  • What exactly are you having trouble with? Looping over an array? Finding a substring in a string? Commented Mar 19, 2012 at 17:00
  • Is it an array of arrays or just an array of strings ? Commented Mar 19, 2012 at 17:02
  • If the second string you're searching for is always going to be a substring of the first string you're searching, why not only search for the first string? Commented Mar 19, 2012 at 17:05
  • Every value that contains 'thisisaverylongstring' will contain 'isavery'. So why don't you look for the short one only? Commented Mar 19, 2012 at 17:08

4 Answers 4

1

If it is a simple as you say it is, you can use stripos (case insensitive string search):

foreach ($array as $element) {
    if (stripos($element, 'isavery') !== false) {
        echo 'Found it!';
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I don't know what's your actual requirement is but as from my understanding the following function could work

  function checkInArray($array, $val)
{
    if(in_array($val,$array))
    return true;    
}
function checkvalinarray($array2D, $val1, $val2)
{
foreach($array2D as $array1D)
{
    if(checkInArray($array1D,$val2))
    return true;    
}
}

Comments

1
$arrayData = array('This is a very long string',
                   'This is a short string',
                  );
$needle = 'very';

$matches = array_filter( $arrayData,
                         function($data) use ($needle) { 
                             return (stripos($data,$needle) !== FALSE); 
                         }
                       );
if (count($matches) > 0) {
    echo 'Match found';
}
var_dump($matches);

Comments

0
$stringToLookFor = 'isavery';
$inArray = FALSE; //does the string exist in the array?
foreach($array as $string)
{
    if(strpos($string, $strongToLookFor) !== FALSE)
    {
         $inArray = TRUE;
    }
}

if($inArray)
{
    echo 'String "' . $stringToLookFor . '" found in array';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.