if elements of array 1 exists in array 2 - php

It's a bit like in_array but while in_array checks the presence of one element in an array and returns true and false accordingly, I want to know whether all elements of array1 is part of array2.
Ex:
$array1 = array(3, 30);
$array2 = array(5, 30);
$array3 = array(5, 50);
$array = array(50,7,8,456,1,5,567);
function new_in_array($array1,$array) // false
function new_in_array($array2,$array) // false
function new_in_array($array3,$array) // true
Any idea?

array_intersect will do:
<?php
$first = array('foo', 'bar');
$second = array('foo', 'bar','baz');
var_dump(array_intersect($first, $second) === $first); // True
$first = array('foo', 'bar', 'hello');
$second = array('foo', 'bar','baz');
var_dump(array_intersect($first, $second) === $first); // False

Use array_intersect to intersect those two and check the number of elements in the return array:
$intersect = array_intersect($array1, $array2);
if (count($intersect) == count($array1)) {
// array1 is fully contained in array2
}

Or use array_diff():
function array_contains($haystack, $needles) {
return !count(array_diff($needles, $haystack));
}
array_contains($array2, $array1); // all elements of array1 is part of array2?

You could also use a for loop.
for ($i = 0; $i < sizeof($array1); $i++) {
if (!in_array($array1[$i], $array2)) {
return False;
}
}
return True;

Related

Array comparison and re-order in PHP

Let's say I Have two arrays.
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
now compare two arrays.if there is no match for value of $arr1 in $arr2 then index is left empty.
for the above arrays output should be:
$arr3 = ['','','C','D']
I tried array_search() function.But couldn't achieve desired output.
Any possible solutions?
You can use foreach with in_array and array_push like:
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
$arr3 = [];
foreach($arr1 as $value){
$arr3[] = (in_array($value, $arr2)) ? $value : '';
}
print_r($arr3);
/*
Result
Array
(
[0] =>
[1] =>
[2] => C
[3] => D
) */
Foreach the first array then test with in_array if exist, if true push into array 3 else push empty value
You can use the following function. In the following code, the function search_in_array return true and false based on the searching within the 2nd array. So you can push the empty or searched value in final array.
<?php
$arr1 = array('A','B','C','D');
$arr2 = array('C','D');
$arr3 = array();
function search_in_array ($value, $array)
{
for ($i=0; $i<count($array); $i++)
{
if ($value == $array[$i])
{
return true;
}
}
return false;
}
for ($i=0; $i<count($arr1); $i++)
{
$value = $arr1[$i];
$result = search_in_array ($value, $arr2);
if ($result)
{
array_push ($arr3, $value);
}
else
{
array_push ($arr3, '');
}
}
print_array($arr3);
?>

How to create php function with output true or false given array all sequence number 1 to n

please help make php function that check whether a given array of integer consists all sequence number from 1 to N. Each number can only appear once in array. Output true/false.
Since you say integer consists all sequence number from 1 to N. Each number can only appear once in array
That means if we compare the array with a range() then the output is true/false.
You can also include a sort in case the arrays are not sorted.
$arr1 = [2,1,3,4,5,6,6,7];
$arr2 = [1,2,3,4,5,6,7];
$arr3 = [1,3,4,5,6,7];
$arr4 = [1,5,6,7,4,3,2];
// sort arrays
sort($arr1);
sort($arr2);
sort($arr3);
sort($arr4);
$n = 7;
$range = range(1,$n);
// or $range(min($array),$n); or $range(min($array),max($array)); depedning on how you want it set up
var_dump($arr1 == $range); //false
var_dump($arr2 == $range); //true
var_dump($arr3 == $range); //false
var_dump($arr4 == $range); //true
https://3v4l.org/DMe46
With the added information, we can use array_intersect and count.
Array intersect returns the matching items in the array.
If we then count them we see if they match.
$arr1 = array(2,3,1,4);
$arr2 = array(2,5,3,4);
$arr3 = array(1,3,4,2,5,6,3);
$range1 = range(1,max($arr1));
$range2 = range(1,max($arr2));
$range3 = range(1,max($arr3));
var_dump(count($range1) == count(array_intersect($arr1, $range1)));
// true
var_dump(count($range2) == count(array_intersect($arr2, $range2)));
// false
var_dump(count($range3) == count(array_intersect($arr3, $range3)));
// false
https://3v4l.org/7Hdll
Each number has to be an integer
Each number has to be bigger than the previous number
Negative number are allowed.
function testInt($my_array)
{
$prevval = null;
foreach ($my_array as $val) {
if ((filter_var($val, FILTER_VALIDATE_INT)) === false) {
return false;
}
if ($prevval !== null) {
if ($val <= $prevval) {
return false;
}
}
$prevval = $val;
}
return true;
}
$test1 = [-1, "4", 5, 7];
$test2 = [0, 1, 2, 100];
$test3 = [1, 4, 4, 100];
$test4 = [1, 5, 4, 1000];
$test5 = [5, 6, 7, "50"];
var_dump(testInt($test1));
bool(true)
var_dump(testInt($test2));
bool(true)
var_dump(testInt($test3));
bool(false)
var_dump(testInt($test4));
bool(false)
var_dump(testInt($test5));
bool(true)

2 PHP arrays for merge

How to delete element from array as it has partial in another?
Other words, I need to compare 2 array likely in_array php function, but partially.
Code:
$a = ['abc', 'cde', 'efg', 'hi'];
$b = ['bce', 'ifg', 'hig'];
// return $b without 'hig' because in $a has partially 'hi'
Thanks very much for any solution!
If you want to make any string in $b not have any string in $a as a substring. demo
<?
$a = ['abc', 'cde', 'efg', 'hi'];
$b = ['bce', 'ifg', 'hig'];
$b = array_filter($b, function($v) use($a){
foreach($a as $str){
if(strpos($v, $str) !== false)
return false;
}
return true;
});
print_r($b);
You can use array_filter() to filter the array with anonymous function. Then a combination of array_diff() and str_split() to compare each letters of each elements. This works even if the letters on the element of $a array is shuffled
$a = ['abc', 'cde', 'efg', 'hi'];
$b = ['bce', 'ifg', 'hig'];
$b = array_filter($b, function($bElem) use($a) {
foreach ($a as $aElem) {
$diff = array_diff(
str_split($aElem),
str_split($bElem)
);
if (empty($diff)) return false;
}
return true;
});
print_r($b);
As I understood, yuo want to compare start of string from $b with full string from $a
$b = array_udiff($b, $a,
function($x, $y) { return strcmp(substr($x, 0, strlen($y)), $y); });
demo
Loop through the array and look for match. If doesn't match any elements of the array, then push the value.
$a = ['abc', 'cde', 'efg', 'hi'];
$b = ['bce', 'ifg', 'hig'];
$result = $a;
foreach ($b as $bs) {
$flag = true;
foreach ($a as $as) {
if (strpos($bs, $as) !== false) {
$flag = false;
}
}
if($flag==true)
array_push($result, $bs);
}
return $result;

How to replace array value with another array value using php?

I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}

Php, in_array with no exactly match

I want to do the following:
$a = array();
$a[] = array(1,2);
$a[] = array(2,5);
$a[] = array(3,4);
var_dump (in_array(array(2,5), $a));
this returns OK, as it expected, but if the source array is not fully matched:
$a = array();
$a[] = array(1,2, 'f' => array());
$a[] = array(2,5, 'f' => array());
$a[] = array(3,4, 'f' => array());
var_dump (in_array(array(2,5), $a));
it returns false. Is there a way to do it with the built-in way, or I have to code it?
in_array() is just not the thing that you should use for this issue. Because it will compare values with type casting, if that's needed. Instead, you may use plain loop or something like:
function in_array_array(array $what, array $where)
{
return count(array_filter($where, function($x) use ($what)
{
return $x===$what;
}))>0;
}
So then
var_dump(in_array_array(array(2, 5), $a)); //true
$needle = array(2, 5);
$found = array_reduce($a, function ($found, array $array) use ($needle) {
return $found || !array_diff($needle, $array);
});
This does an actual test of whether the needle is a subset of an array.
function subset_in_array(array $needle, array $haystack) {
return array_reduce($haystack, function ($found, array $array) use ($needle) {
return $found || !array_diff($needle, $array);
});
}
if (subset_in_array(array(2, 5), $a)) ...

Categories