Search code examples
phparraysarray-uniquearray-intersect

How to have value follow each other in PHP?


How do I find the values in an array that matches another array in order?

Here is my code that gives me the $Array4 which does not correspond to the expected result (given below):

<?php
for ($j=0; $j < 1; $j++) {
    for ($i=0; $i < 100; $i++) {
        $Array3 = (array_intersect($Array2, $Array1));
        $Array4 = array_unique($Array3);
    }

print_r($Array4);
}
?>

$Array1 :

[not] => G
[have] => L

$Array2 - Array who match with $Array1:

[Once] => B
[uppon] => A
[a] => G
[time] => M
[,] => Z
[a] => V
[small] => G
[squirrel] => F
[,] => Z
[whitch] => U
[once] => L
[in] => N
[the] => N
[forest] => X
[,] => Z
[set] => G      \\Search 
[out] => L      \\string
[to] => V
[find] => M
[something] => N
[to] => W
[eat] => X
[,] => Z
[to] => G
[survive] => G
[.] => Z

The result with my code:

$Array3 - with duplicates:

[a] => G
[small] => G
[once] => L
[set] => G     \\Search 
[out] => L     \\string
[to] => G

$Array4 - The result (the problem being that "a" and "once" do not follow each other in the array $Array2) :

[a] => G
[once] => L

The expected result:

[set] => G    \\Search 
[out] => L    \\string 

Solution

  • This would hopefully do what you are looking for.

    function findSameInPosition($needle, $haystack) {
        $indexedNeedle = array_values($needle);
        $indexedHaystack = array_values($haystack);
        foreach (array_keys($indexedHaystack) as $key) {
            if (array_slice($indexedHaystack, $key, count($indexedNeedle)) === $indexedNeedle) {
                return array_slice($haystack, $key, count($indexedNeedle));
            }
        }
    }
    
    // Example:
    
    $input1 = array(
        "not" => "G",
        "have" => "L"
    );
    
    $input2 = array(
        "Once" => "B",
        "uppon" => "A",
        "a" => "G",
        "time" => "M",
        "," => "Z",
        "a" => "V",
        "small" => "G",
        "squirrel" => "F",
        "," => "Z",
        "whitch" => "U",
        "once" => "L",
        "in" => "N",
        "the" => "N",
        "forest" => "X",
        "," => "Z",
        "set" => "G",
        "out" => "L",
        "to" => "V",
        "find" => "M",
        "something" => "N",
        "to" => "W",
        "eat" => "X",
        "," => "Z",
        "to" => "G",
        "survive" => "G",
        "." => "Z"
    );
    
    findSameInPosition($input1, $input2); // Returns Array ( [set] => G [out] => L )