Comments

dhtml

Sat 29 Dec, 2018 03:50 pm

the question is not really clear like that o, is omni.potens.2019 meant to be searched as is in the second array?

omnipotens

Sat 29 Dec, 2018 04:01 pm

The problem is to check that $arrayA which has value of 'omni.potens.2019' exists in $arrayB. Once there's a match, it should return true.

dhtml

Sat 29 Dec, 2018 04:16 pm

something like "2018.omni.potens.2019" should return true?

wale2

Sat 29 Dec, 2018 04:24 pm

I don't know much about PHP but the logic should be somewhat similar, I guess.

I C#. I could do this:

var arr3 = arr2.Intersect(arr1); //Given that the arrays are of the same type.

In your case, the result would be:

2016.omni.potens.2019

Even better, if you are searching for a single result. 

var theResult=arr2.Intersect(arr1).FirstOrDefault();

A simple check to find out whether the condition is true:

bool exists = (theResult == null) ? false : true;

There are other ways to go about this but I guess you got the idea. The logic should be similar in PHP.

omnipotens

Sat 29 Dec, 2018 05:43 pm

@dhtml See what I mean.

I am trying to check if 'omni.potens.2019' of $arrayA exists in any of the array values of $arrayB.

dhtml

Sat 29 Dec, 2018 05:54 pm

Let me write this in PHP, there are 2 possible ways: try this:

<?php
$arrayA = ['omni.potens.2019'];
$arrayB = ['2016.omni.potens.2019','2017.omni.potens.2019','2018.omni.potens.2019'];

function arr_search($haysack,$needle,$partial=false) {
$result=Array();
foreach($needle as $item) {
  foreach($haysack as $key=>$hay) {
    if($partial && strpos($hay,$item)) {
      $result[]=$hay;
    } else if($hay==$item) {
      $result[]=$hay;
    }
  }
}
return $result;
}

$result=arr_search($arrayB,$arrayA,true);

$result=arr_search($arrayB,$arrayA,false);


omnipotens

Mon 31 Dec, 2018 08:15 am

@dhtml Thanks for the heads up. I tweaked it to the below code to get exactly what I wanted.

$arrayA = ['omni.potens.2019'];

$arrayB = ['2016.omni.potens.2019','2017.omni.potens.2019','2018.omni.potens.2019'];

function arr_search($haysack,$needle,$partial=false) {
$result='';
foreach($needle as $item) {
  foreach($haysack as $key=>$hay) {
	do {
    if($partial && strpos($hay,$item)) {
      $result = 'found';
	} else if($hay==$item) {
      $result=$hay;
    }
  }
	while (0);
}
return $result;
}
}


$result=arr_search($arrayB,$arrayA,true);
var_dump($result);
$result=arr_search($arrayB,$arrayA,false);
var_dump($result);

I  discovered something that I'll like to know if anyone has a solution to. strpos would always match '2016.omni.potens.2019x' and 'omni.potens.2019'. Is there a way to make for a strict matching?