Create an array from arrays that holds data - php

I am trying to create an array that will hold the only array that contains values.
Code below works well, but I get trouble if for ex, $array2 (but can array1 or array3) doesn't contain any value. In that case, I need to merge only array1 and array3.
$array3 = array_filter( array_map( function( $term ) {
if ( ! $term = \Softing\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
];
}, $terms ) );
$formatted_terms[] = array_merge($array1, $array2, $array3);
Each if three arrays are formed on the same way as $array3, but some of them could be empty, no values. Those Arrays I dont want to merge. Want to create array only from arrays that holds value.
What is the easiest way to accomplish this.
I tried using
$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);
Any advice ?

You can use array_filter() to remove empty array values. Since you have a multidimensional array, you may consider using array_map() in conjunction with array_filter().
Take the following for example:
$array1 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];
$array2 = false;
$array3 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];
$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);
$formatted_terms = array_map('array_filter',$formatted_terms);
echo '<pre>',print_r($formatted_terms),'</pre>';
https://www.php.net/manual/en/function.array-map.php
https://www.php.net/manual/en/function.array-filter.php

Just check if theyre an array and if theyre not empty. If so, use array merge. If not, just do nothing.
$a_all_arrays = array($array1, $array2, $array3);
$a_merged = array();
foreach($a_all_arrays as $arr)
{
if(is_array($arr) && !is_empty($arr))
{
$a_merged = array_merge($a_merged, $arr);
}
}

Check the array if it has values before merging,
$array1=!empty($array1) && is_array($array1)?$array1:[];
$array2=!empty($array2) && is_array($array2)?$array2:[];
$array3=!empty($array3) && is_array($array3)?$array3:[];
$formatted_terms[] = array_merge($array1, $array2, $array3);

Related

How to check it elemets of an array are in another array

I have an issue,
I have this array
$items= array('ABC','DEF',GHI');
and have another two arrays
$array1 = array('ABC','DEF',GHI');
$array2 = array('DEF');
$array1 should return TRUE because all elements are in $items
$array2 should return FALSE because 'ABC' and 'GHI' arent in that array
i've tried with array_intersect and array_diff but i cant get it,
$result = array_intersect($items,$array1);
$result = !array_diff($items,$array1);
Could you please help me?
Regards
Mario
To see if the array contains at least all values in $items, just get all values from the array that are also in $items and compare it with $items:
$result = (array_intersect($array1, $items) == $items);
If you just need to compare the arrays:
$result = ($array1 == $items);
But why is this not working for you:
$result = !array_diff($items, $array1);
If you dont want to use array_diff, you can use the multidimensional arrays.
Put your arrays inside another array:
$items1= array(
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"DEF"),
);
Check them with conditional statements:
if($items1[0]==$items1[1]){
echo "true";
}if($items1[1]==$items1[2]){
echo "true 2";
}else{
echo "false";
}

How to remove an entire row in multidimentional array based on another simple array value

i need to compare the value of an array and based on that i need to check another array which is multidimensional , if the value is present in another array , then i need to delete the entire row from it . how to achieve this ?
<?php
$a1=array(
array("key1"=>"123","phone"=>"2234567890","val"=>"test1","color"=>"red"),
array("key1"=>"234","phone"=>"2234567890","val"=>"test2","color"=>"green"),
array("key1"=>"312","phone"=>"2234567890","val"=>"test3","color"=>"yellow"),
array("key1"=>"425","phone"=>"2234567890","val"=>"test4","color" => "orange"));
$a2=array("green");
foreach($a1 as $k => $value){
$result = array_diff($value, $a2);
print_r($result);
}
?>
I have tried with array_diff , but only that key,val pair is removing .. i need to remove entire row.
$a2 array has value "green" .. based on this array $a1 should have only 3 array as output by removing 2nd array of $a2.
Assuming you compare values of color key:
$a1 = array(
array("key1"=>"123","phone"=>"2234567890","val"=>"test1","color"=>"red"),
array("key1"=>"234","phone"=>"2234567890","val"=>"test2","color"=>"green"),
array("key1"=>"312","phone"=>"2234567890","val"=>"test3","color"=>"yellow"),
array("key1"=>"425","phone"=>"2234567890","val"=>"test4","color" => "orange")
);
$a2 = array("green");
$newArray = array_filter(
$a1,
function($v) use ($a2) { return !in_array($v['color'], $a2); }
);
Fiddle here.
If you don't want to compare a specific key, then just check if it is in the array and unset it:
foreach($a1 as $k => $value){
if(array_intersect($value, $a2)) {
unset($a1[$k]);
}
}
This would also work for checking an array with multiple values like:
$a2 = array("green", "test4");
//or
$a2 = array("green", "red");

PHP array_merge if not empty

Trying to merge 4 arrays, but some may be empty at certain times.
$array_1 = array('something1', something2);
$array_2 = array('something3', something4);
$array_3 = array();
$array_4 = array('something1', something2);
$list = array_merge($array_1,$array_2,$array_3,$array_4);
print_r($list);
But if one of the arrays are empty, there will be an error.
I've been googling forever, but I can't find a solid simple answer on how to check for empty arrays before merging.
Argument #2 is not an array
Or whichever array is empty is the argument number. How do I strip out empty arrays before merging?
There is NO error with an empty array. There is only an error if the arg is NOT an array.
You could check is_array() or:
$list = array_merge(
(array)$array_1,
(array)$array_2,
(array)$array_3,
(array)$array_4
);
Okay here you go, this should do the trick (if you make array of the initial arrays):
$arrs = array();
$arrs[] = array('something1', something2);
$arrs[] = array('something3', something4);
$arrs[] = array();
$arrs[] = array('something1', something2);
$list = array();
foreach($arrs as $arr) {
if(is_array($arr)) {
$list = array_merge($list, $arr);
}
}
print_r($list);
Array merge supports empty array()
Doc:
Example #3 Simple array_merge() example
http://us1.php.net/array_merge
<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>
Result
Array
(
[0] => data
)
You are getting notice because something2, something4 should be quoted as string or $ as variable.
PHP Notice: Use of undefined constant something2 - assumed 'something2'

php - finding keys in an array that match a pattern

I have an array that looks like:
Array ( [2.5] => ABDE [4.8] => Some other value )
How would I find any key/value pair where the key matches a pattern? I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".
I was thinking about using a regular expression with a pattern like:
$prefix = 2;
$pattern = '/'.$prefix.'\.\d/i';
and then looping through the array and checking each key. (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).
I'm wondering if there's a simpler way to do this?
Thanks.
I think you need something like this:
$keys = array_keys($array);
$result = preg_grep($pattern, $keys);
The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.
Have a look at the preg_grep function.
you can simply loop through the array and check the keys
$array = array(...your values...);
foreach($array as $key => $value) {
if (preg_match($pattern,$key)){
// it matches
}
}
You can wrap it in a function and pass your pattern as parameter
Old question, but here's what I like to do:
$array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ];
preg_grep + array_keys will find all keys
$keys = preg_grep( '/^2\.\d/i', array_keys( $array ) );
You can add array_intersect_key and array_flip to extract a slice of the array that matches the pattern
$vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) );
For future programmers who encounter the same issue. Here is a more complete solution which doesn't use any loops.
$array = ['2.5'=> 'ABCDE', '2.9'=>'QWERTY'];
$keys = array_keys($array);
$matchingKeys = preg_grep('/^2\.+/', $keys);
$filteredArray = array_intersect_key($array, array_flip($matchingKeys));
print_r($filteredArray);
That are my ways
$data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];
// FIRST WAY
$keys = array_keys($data);
if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
return myReturn(false, "Dados pendentes");
}
// SECOND WAY
$keys = implode("," array_keys($data));
if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
return myReturn(false, "Dados pendentes");
}
To get just the part of the array with matching keys you could also write
$matching_array = array_flip(preg_grep($pattern, array_flip($your_array)));
This might just lead to problems performance-wise, if your array gets too big.
There's T-Regx library for regular expression in PHP, and it kas preg::grep_keys() method.
<?php
$array = [2.5 => 'ABDE', 4.8 => 'Some other value'];
preg::grep_keys("/$prefix\.\d/i", $array);

how to get keys that correspond to different values in two arrays?

$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
I need function that would return array('tomato','banana'), consider that it omits keys that don't exist in one or the other array. Apple has the same value in both arrays, so it should be omitted - returned should be only keys whose values differ and are set
This should work (demo):
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$result = array_keys(array_diff(array_intersect_key($arr1, $arr2), $arr2));
print_r($result);
Output:
Array
(
[0] => tomato
[1] => banana
)
Reference:
array_intersect_key — Computes the intersection of arrays using keys for comparison
array_diff — Computes the difference of arrays
array_keys — Return all the keys or a subset of the keys of an array
$array3 = array();
foreach(array_intersect_key($array1, $array2) as $key => $v){
if($array1[$key] != $array2[$key]) $array3[] = $key;
}
<?php
/**
* Returns an array which contains keys which are in both $array1
* and $array2, and which have different values.
*/
function getKeysWhichMatchAndHaveDifferentValues($array1, $array2)
{
$arrIntersected = array_intersect_key($array1, $array2);
foreach($arrIntersected as $key => $value)
{
if($array2[$key] == $value) {
unset($arrIntersected[$key]);
}
}
return array_keys($arrIntersected);
}
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$final = getKeysWhichMatchAndHaveDifferentValues($arr1, $arr2);
echo '<pre>' . print_r($final) . '</pre>';
?>
I would do simple loop.
Of course if you will need to compare large arrays, the native PHP functions could help a lot. Still can't answer right now what would be the most optimal way to do this.
You could do this using array_intersect and array_keys.
$arr3 = array_intersect(array_keys($arr1), array_keys($arr2));

Categories