Skip to content
TheChatArchiveThe Chat Archive
Mistralmistral-small-2506· Mistral AIHugging Face LMArena Human Preference 140K

Przeszukaj w PHP 8.2 dwie tablice i zwróć część wspólną

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with MiniMaxminimax-m1’s answer.
  1. User

    Przeszukaj w PHP 8.2 dwie tablice i zwróć część wspólną

  2. Mistral Assistant

    Znajdowanie części wspólnej dwóch tablic w PHP 8.2

    W PHP 8.2 możesz znaleźć część wspólną dwóch tablic (tzn. elementy, które występują w obu tablicach) na kilka sposobów. Oto kilka metod:

    Metoda 1: Użycie funkcji array_intersect()

    $array1 = [1, 2, 3, 4, 5];
    $array2 = [4, 5, 6, 7, 8];
    
    $commonElements = array_intersect($array1, $array2);
    
    print_r($commonElements);
    // Wyświetli: Array ( [3] => 4 [4] => 5 )
    

    Metoda 2: Użycie operatora array_intersect z funkcją strzałkową

    $array1 = ['a', 'b', 'c', 'd'];
    $array2 = ['c', 'd', 'e', 'f'];
    
    $commonElements = array_intersect($array1, $array2);
    
    print_r($commonElements);
    // Wyświetli: Array ( [2] => c [3] => d )
    

    Metoda 3: Użycie funkcji array_intersect z porównaniem kluczy i wartości

    $array1 = ['a' => 1, 'b' => 2, 'c' => 3];
    $array2 = ['b' => 2, 'c' => 3, 'd' => 4];
    
    $commonElements = array_intersect_assoc($array1, $array2);
    
    print_r($commonElements);
    // Wyświetli: Array ( [b] => 2 [c] => 3 )
    

    Metoda 4: Użycie pętli foreach (dla większej kontroli)

    $array1 = [10, 20, 30, 40];
    $array2 = [30, 40, 50, 60];
    $commonElements = [];
    
    foreach ($array1 as $value) {
        if (in_array($value, $array2)) {
            $commonElements[] = $value;
        }
    }
    
    print_r($commonElements);
    // Wyświetli: Array ( [0] => 30 [1] => 40 )
    

    Metoda 5: Użycie funkcji array_filter z funkcją strzałkową

    $array1 = ['x', 'y', 'z', 'w'];
    $array2 = ['y', 'z', 'a', 'b'];
    
    $commonElements = array_filter($array1, fn($value) => in_array($value, $array2));
    
    print_r($commonElements);
    // Wyświetli: Array ( [1] => y [2] => z )
    

    Wybór metody zależy od Twoich potrzeb - najprostsze i najczęściej używane jest array_intersect().

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.