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'
Related
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);
well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help
I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.
Sorry for the confusing title...
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn't seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I "print_r" the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I'm populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname" is a string, not an array. call_user_func_array will pass each element in $arr_results as argument to array_intersect. array_intersect expects arrays as arguments, but each item in $arr_results is a string, not an array.
All you have to do is create an array of arrays instead of array names:
$arr_results = array();
foreach($arr_words as $word) {
$ids = array();
while ($row = mysql_fetch_assoc($search)) {
$ids[] = $row['id'];
}
$arr_results[] = $ids;
}
$matches = call_user_func_array('array_intersect',$arr_results);
I turn $arrayname into an array with $$arrayname = array();
Right, you create a variable, lets say arr_0 which will point to array. But there is still a difference between the variable name arr_0 and the string containing the variable name "arr_0". You create an array of strings, and that just won't work. PHP does not know that the string contains a name of a variable. For example, consider this:
$arr = "arr_0";
echo $arr[0];
Based on your logic, it should output the first element of the array, but it does not, because $arr is a string, not an array, although it contains the name of a variable.
You'd have to use eval, but you really should not. You could also use variable variables again:
array_push($arr_results, $$arrayname);
that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.
$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));