Lets say we have two 2D array:
thisArray = array(
array('A', 'B', '');
array('A', 'B', '');
)
How to check is thisArrays arrays all have empty values at index 2 and if they do all have empty elements at index 2, how to remove those elements from all arrays?
I can't seem to figure this out and I can't seem to google out any php functions which would help me.
Using array_column(), and array_filter, you can achieve this,
array_column - gives you array in one direction
array_filter - filter, empty values,
So in the end if array is empty, then all are empty
<?php
$array = array(
array('A', 'B', ''),
array('A', 'B', '')
);
if(empty( array_filter(array_column($array,2))) ){
echo 'All are empty at index 2'.PHP_EOL;
// since all are empty
// use reference and unset
foreach($array as &$item) {
unset($item[2]);
}
// unset reference
unset($item);
}
print_r($array);
?>
Test Results:
$ php test.php
All are empty at index 2
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => Array
(
[0] => A
[1] => B
)
)
$thisArray = array(
array('A', 'B', '');
array('A', 'B', '');
)
Try this
foreach($thisArray as $array){
if(isset($array[2]) && $array[2]==null){ //if array at index 2 is empty
unset($array[2])); //remove array
}
}
return $thisArray;
Related
This question already has answers here:
PHP append one array to another (not array_push or +)
(11 answers)
Closed last month.
I have two arrays that are inside foreach loop, I want to merge them to one key and value.
let the first array "array1" inside foreach:
$array1 = ['x', 'y', 'z'];
let the second array "array2" inside foreach:
$array2 = ['a', 'b', 'c'];
Expected output should be as follows:
$mergeArray = [0=>['x', 'y', 'z','a', 'b', 'c']];
What I have done is the following:
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[] = $value['items1'];
$mergeArray[] = $value['items2'];
echo '<pre>';
print_r($mergeArray);
exit;
}
Thanks and welcome all suggestions
Use array_merge:
$mergeArray[] = array_merge($value['item1'], $value['item2']);
Also, the exit should not be in the loop, that will prevent the loop from repeating.
You can do it with this code
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[0] =array_merge ( $value['items1'], $value['items2']);
echo '<pre>';
print_r($mergeArray);
exit;
}
Why use a foreach loop at all? Am I missing something?
$array1 = array('x', 'y', 'z');
$array2 = array('a', 'b', 'c');
$mergeArray[0] = array_merge($array1, $array2);
Output:
Array
(
[0] => Array
(
[0] => x
[1] => y
[2] => z
[3] => a
[4] => b
[5] => c
)
)
If I have an associative array that is structured like
(
1 => 'a',
2 => 'b',
0 => 'c'
)
where all of the keys are numeric, will array_values ALWAYS guarantee that the values occur chronologically, in the new array, based on their previous keys' values, i.e. ['c', 'a', 'b']?
If not, how can I accomplish this instead?
No, array_values() will not reorder the values in any way. It doesn't care about keys.
Its effective implementation is basically this:
function array_values_impl(array $array)
{
$newArray = [];
foreach ($array as $item) {
$newArray[] = $item;
}
return $newArray;
}
If you want to sort the array using the keys, use ksort().
You can accomplish by first sorting the array with keys and getting values by array_values function.
For example
$array = array(
1 => 'a',
2 => 'b',
0 => 'c'
);
ksort($array);
print_r(array_values($array));
Output:
Array
(
[0] => c
[1] => a
[2] => b
)
How can I get all indexes of an array that have a certain value? array_search() only gives me the first index, but I want all of the indexes. Is there a way to do this
This: array_search( 'a', array( 'a', 'b', 'a' ) ); would return 0 but what really want in this case would be 0 and 2.
array_search() will only return the found key, You should use array_keys with the second parameter as your needle, it will return both indices 0 and 2:
$key = 'a';
$array = array('a', 'b', 'a');
$found = array_keys($array, $key);
print_r($found); // Array ( [0] => 0 [1] => 2 )
I have an array like:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
)
[2] => Array
(
[0] => d
[1] => e
[2] => f
)
)
I want to convert my array to a string like below:
$arrtostr = 'a,b,c,d,e,f';
I've used implode() function but it looks like it doesn't work on two-dimensional arrays.
What should I do?
Alternatively, you could use a container for that first, merge the contents, and in the end of having a flat one, then use implode():
$letters = array();
foreach ($array as $value) {
$letters = array_merge($letters, $value);
}
echo implode(', ', $letters);
Sample Output
Given your subject array:
$subject = array(
array('a', 'b'),
array('c'),
array('d', 'e', 'f'),
);
Two easy ways to get a "flattened" array are:
PHP 5.6.0 and above using the splat operator:
$flat = array_merge(...$subject);
Lower than PHP 5.6.0 using call_user_func_array():
$flat = call_user_func_array('array_merge', $subject);
Both of these give an array like:
$flat = array('a', 'b', 'c', 'd', 'e', 'f');
Then to get your string, just implode:
$string = implode(',', $flat);
You asked for a two-dimensional array, here's a function that will work for multidimensional array.
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
I can flatten an array structure like so:
$multidimensional_array = array(
'This',
array(
'is',
array(
'a',
'test'
),
array(
'for',
'multidimensional',
array(
'array'
)
)
)
);
echo implode_r(',', $multidimensional_array);
The results is:
This,is,a,test,for, multidimensional,array
I have an array which may contain numeric or associative keys, or both:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
Finding the right element to remove is no issue, it's the keys that are the problem. unset doesn't renumber the keys, and array_splice works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1) would remove the "bar" element rather than the "d" element).
This should re-index the array while preserving string keys:
$x = array_merge($x);
You can fixet with next ELEGANT solution:
For example:
<?php
$array = array (
1 => 'A',
2 => 'B',
3 => 'C'
);
unset($array[2]);
/* $array is now:
Array (
1 => 'A',
3 => 'C'
);
As you can see, the index '2' is missing from the array.
*/
// SOLUTION:
$array = array_values($array);
/* $array is now:
Array (
0 => 'A',
1 => 'C'
);
As you can see, the index begins from zero.
*/
?>
I've come up with this - though I'm not sure if it's the best:
// given: $arr is the array
// $item is the item to remove
$key = array_search($item, $arr); // the key we need to remove
$arrKeys = array_keys($arr);
$keyPos = array_search($key, $arrKeys); // the offset of the item in the array
unset($arr[$key]);
array_splice($arrKeys, $keyPos, 1);
for ($i = $keyPos; $i < count($arrKeys); ++$i) {
if (is_int($arrKeys[$i])) --$arrKeys[$i]; // shift numeric keys back one
}
$arr = array_combine($arrKeys, $arr); // recombine the keys and values.
There's a few things I've left out, just for the sake of brevity. For example, you'd check if the array is associative, and also if the key you're removing is a string or not before using the above code.
Try array_diff() it may not order the new array correctly though
if not the following should work
You will need to iterate over it in the remove function.
function remove($x,$r){
$c = 0;
$a = array();
foreach ($x as $k=>$v){
if ($v != $r) {
if (is_int($k)) {
$a[$c] = $v;
$c++;
}
else {
$a[$k] = $v;
}
}
}
return $a;
}
DC
I don't think there is an elegant solution to this problem, you probably need to loop to the array and reorder the keys by yourself.