Home >Backend Development >PHP Problem >How to determine how many values ​​in two arrays are the same in php

How to determine how many values ​​in two arrays are the same in php

青灯夜游
青灯夜游Original
2022-05-17 16:04:512876browse

Method: 1. Use array_intersect() to compare arrays, the syntax "array_intersect(array 1, array 2)" will return an intersection array; 2. Use count() to get the length of the intersection array, the syntax "count (array)", the length of the returned array is the number of elements with the same value.

How to determine how many values ​​in two arrays are the same in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php determines two arrays There are several methods with the same values

1. Use the array_intersect() function to compare two arrays and obtain the intersection elements

array_intersect() function Used to compare the values ​​of two (or more) arrays and return an intersection array.

<?php
header("Content-type:text/html;charset=utf-8");
$arr1=array(32,1,3,6,8,34,12,7);
$arr2=array(1,8,3,12,5,32,7,8);
var_dump($arr1);
var_dump($arr2);
$intersect=array_intersect($arr1,$arr2);
echo "两个数组的交集:";
var_dump($intersect);
?>

How to determine how many values ​​in two arrays are the same in php

It can be seen that the returned intersection array contains elements with the same value in both arrays.

You only need to calculate the length of the intersection array to know how many values ​​in the two arrays are the same.

2. Use count() to get the length of the intersection array

The count() function can count the number of all elements in the array, or the number of attributes in the object. .

$len=count($intersect);
echo "两数组中值相同的元素有: ".$len." 个";

How to determine how many values ​​in two arrays are the same in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine how many values ​​in two arrays are the same in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn