PHP: How to set value into empty index in an Array? - php

I have array in my PHP, for example:
array
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] => Grape
[6] => Apple
[7] => Pineaple
[8] => Avocado
[9] => Banana
)
)
and I need to fill the empty element (index 0 upto 4) with new value from an array or $variable.
Maybe for example, I get the data from another array:
newArray
Array
(
[0] => Array
(
[0] => Lemon
[1] => Lime
[2] => Mango
[3] => Watermelon
[4] => Starfruit
)
)
so I can get a result like this:
finalArray
Array
(
[0] => Array
(
[0] => Lemon
[1] => Lime
[2] => Mango
[3] => Watermelon
[4] => Starfruit
[5] => Grape
[6] => Apple
[7] => Pineaple
[8] => Avocado
[9] => Banana
)
)
Any help would be appreciated. Thanks

You can loop through your array, check if the index is empty and then, set it's value.
<?php
foreach($array as $index=>$value)
{
if(empty($array[$index]))
{
$array[$index] = $newValue;
}
}

<?php
$array=array("0"=>"","1"=>"","2"=>"","5"=>"Grape","6"=>"Apple","7"=>"Pineaple","8"=>"Avocado","9"=>"Banana");
echo "<pre>";print_r($array);echo"</pre>";
$newarray= array();
foreach($array as $key => $value){
if($value == ''){
//echo $key."<br>";
$value = 'Somevalue';
}
$newarray[] = $value;
//echo "<pre>";print_r($value);echo"</pre>";
}
echo "<pre>";print_r($newarray);echo"</pre>";
?>
Link

There is already a function in a standard library called array_replace. If the new values in the other array have the same indices you can use it:
$result = array_replace($array1, $array2);
If you just need to set up default values for empty elements use array_map:
$defaultValue = 'Foo';
$result = array_map(function ($item) use ($defaultValue) {
return $item ?: $defaultValue;
}, $array1);
Here is working demo.

Use only array_merge() function
For Example
print_r( array_merge($array, $newarray) );

Related

PHP array_keys multiple levels

I have array1 like this:
Array
(
[0] => 123
[1] => 456
[2] => 789
)
And array 2 like this
Array
(
[0] => Array
(
[0] => some text
[1] => 888
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 999
[2] => some
[3] => text
)
[3] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[4] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
I am checking only 1. column of second array and finding values that match values from first array. This is my code:
$test=array();
$xcol = array_column($array2, 1);
foreach( $array1 as $key => $value ) {
if( ($foundKey = array_keys($xcol, $value)) !== false ) {
$rrt=$foundKey;
foreach($rrt as $rte){
$test[]=$array2[$rte];
}
}
}
echo "<pre>";
print_r($test);
echo "</pre>";
It is working and giving me proper results but it does not check for all levels. Can anybody please point me what am I doing wrong?
My output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
And desired output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
Solution:
create a loop which loop your $array2 which holds datas you wanted to get whos values match in first array $array1
foreach($array2 as $data) {
Inside loop create another loop which loop your indexes
foreach($data as $value) {
But before than create a condition if your index value is array loop it and check it it's index value is match in any indexes from $array1 use php function in_array for that
if (gettype($value) == "array") {
foreach($value as $val) {
if (in_array($val, $array1) ) {
$result[] = $data;
Then if you find it just stop the loop using break to avoid duplication
break;
}
}
Else you just directly use in_array
} else if (in_array($value, $array1)) {
$result[] = $data;
}
}
}
Just grab the code here in Demo
Help it helps just mark it answer if you are satisfied to it
Lets make a recursive method for this. What is recursion you ask? Well it is simply a method that calls it self.
<?php
$array1 = array(123,456,789);
$array2 = array(
array(
"some text"
, 888
, "some"
, "text"
),
array(
"some text"
,123
,"some"
,"text"
),
array(
"some text"
,999
,"some"
,"text"
),
array(
"some text"
,array(456,789)
,"some"
,"text"
),
array(
"another text"
,123
,"some"
,"text"
)
);
$final = array();
foreach($array1 as $needle){
foreach($array2 as $haystack){
if(find($needle,$haystack)){
$final[] = $haystack;
}
}
}
print_r($final);
function find($needle, $haystack){
$result = false;
foreach ($haystack as $value) {
if(is_array($value)){
$result = find($needle, $value);
} else {
if($needle == $value){
$result = true;
}
}
}
return $result;
}

Unset value from array by value, not key

I have the following array:
Array (
[0] => 1
[1] => 2
[2] => 2
[3] => 4
[4] => 4
[5] => 8)
I want to remove some items of the array but by value, not by key. How I can do that if I want to remove all the items with the value "4", or with the value "x"?
Use array_search
$key = array_search(4, $arr);
unset($arr[$key]);
If occurences of value in array is more than once use array_keys:
$keys = array_keys($arr, 4);
foreach ($keys as $k)
unset($arr[$k]);
you could try it this way:
<?php
$data = array('haha', 'hehe', 'hihi', 'gtfo', 'hoho', 'huhu');
$data = preg_grep('/^(?!gtfo).*$/', $data);
print_r($data);
?>
Output:
Array
(
[0] => haha
[1] => hehe
[2] => hihi
[4] => hoho
[5] => huhu
)

How to remove the parent numeric keys of php array

I've an array in php something like below
Array
(
[0] => Array
(
[0] => 40173
[1] => 514081
[2] => 363885
[3] => 891382
),
[1] => Array
(
[0] => 40173
[1] => 5181
[2] => 385
[3] => 891382
)
)
Now I want to remove the parents indexes 0,1... and finally want to get all the values (only unique values).
Thanks.
One possible approach is using call_user_func_array('array_merge', $arr) idiom to flatten an array, then extracting unique values with array_unique():
$new_arr = array_unique(
call_user_func_array('array_merge', $old_arr));
Demo. Obviously, it'll work with array of any length.
$startArray = Array
(
[0] => Array
(
[0] => 40173
[1] => 514081
[2] => 363885
[3] => 891382
),
[1] => Array
(
[0] => 40173
[1] => 5181
[2] => 385
[3] => 891382
)
);
//Edited to handle more the 2 subarrays
$finalArray = array();
foreach($startArray as $tmpArray){
$finalArray = array_merge($finalArray, $tmpArray);
}
$finalArray = array_unique($finalArray);
Using RecursiveArrayIterator Class
$objarr = new RecursiveIteratorIterator(new RecursiveArrayIterator($yourarray));
foreach($objarr as $v) {
$new_arr[]=$v;
}
print_r(array_unique($new_arr));
Demo
OUTPUT:
Array
(
[0] => 40173
[1] => 514081
[2] => 363885
[3] => 891382
[5] => 5181
[6] => 385
)
$new_array = array_merge($array1, $array2);
$show_unique = array_unique($new_array);
print_r($show_unique);
array_merge is merging the array's, array_unique is removinge any duplicate values.
Try something like this:
$new_array = array();
foreach($big_array as $sub_array) {
array_merge($new_array, $sub_array);
}
$new_array = array_unique($new_array);
(code not tested, this just a concept)
Try this:
$Arr = array(array(40173, 514081, 363885, 891382),
array(40173,5181, 385,891382));
$newArr = array();
foreach($Arr as $val1)
{
foreach($val1 as $val2)
{
array_push($newArr, $val2);
}
}
echo '<pre>';
print_r(array_unique($newArr));
Output:
Array
(
[0] => 40173
[1] => 514081
[2] => 363885
[3] => 891382
[5] => 5181
[6] => 385
)
Refer: https://eval.in/124240
--
Thanks

Multiple arrays with same indexs in php

Hi I want to save records from array in php.I get arrays like
Array
(
[0] => Make
[1] => Model
[2] => Year
[3] => SKU
)
Array
(
[0] => HTC
[1] => Diamond
[2] => 2008
[3] => HTC Touch Diamond
)
Array
(
[0] => Samsung
[1] => M-900
[2] => 2007
[3] => MM-A900M
)
Array
(
[0] => AT&T
[1] => PDA
[2] => 2002
[3] => 8525PDA
)
Array
(
[0] => AT&T
[1] => PDA
[2] => 2003
[3] => 8525PDA
).
The above data coming from foreach loop like foreach($data as $row){ print_r($row);}.Now i want to save lower records against first array indexs like make,model,year and sku.The array index( make,model,year,sku) can be less or more means dynamic.How can i do that ? Thnaks
Try this :
$cnt = 0;
$res = array();
foreach($data as $row){
if($cnt ==0){
$key = array();
$key = $row;
$cnt++;
}
else{
$res[] = array_combine($key,$row);
}
}
echo "<pre>";
print_r($res);
Use build-in function array_combine

Remove first levels of identifier in array [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 10 months ago.
I think this has been up before, but could'nt find any answer to it. If it's already answered please point me in the right direction with a link.
I have an array that I wan't to remove the first levels of identifier. I think there is a function for this?
Example of how it is:
[0] => Array
(
[8] => Röd
)
[1] => Array
(
[8] => Blå
)
[2] => Array
(
[6] => Bobo
)
[3] => Array
(
[8] => Grön
)
[4] => Array
(
[7] => Sten
)
[5] => Array
(
[8] => Vit
)
[6] => Array
(
[7] => Guld
)
[7] => Array
(
[6] => Lyxig
)
What I wan't
[8] => Röd
[8] => Blå
[6] => Bobo
[8] => Grön
[7] => Sten
[8] => Vit
[7] => Guld
[6] => Lyxig
Try to merge array with splat operator:
print_r(array_merge(...$array));
The problem here is preserving the keys for the identifier you want. You have some names strings that have the same key (like Blå and Röd). You either need to store these in an array or be willing to lose the key.
Example with php5.3:
$processed = array_map(function($a) { return array_pop($a); }, $arr);
This will give you:
[0] => Röd
[1] => Blå
[2] => Bobo
[3] => Grön
[4] => Sten
[5] => Vit
[6] => Guld
[7] => Lyxig
It has become clear the keys on the inner array need to be preserved because they are some kind of id. With that said you must change the end structure you're going for because you can have 2 of the same key in a single array. The simplest structure then becomes:
[8] => Array
(
[0] => Röd,
[1] => Blå,
[2] => Vit,
[3] => Grön
)
[6] => Array
(
[0] => Bobo,
[1] => Lyxig
)
[7] => Array
(
[0] => Sten,
[1] => Guld
)
To get this structure a simple loop will work:
$processed = array();
foreach($arr as $subarr) {
foreach($subarr as $id => $value) {
if(!isset($processed[$id])) {
$processed[$id] = array();
}
$processed[$id][] = $value;
}
}
PHP array_column
$new_array = array_column($old_array,0);
This will retrieve the value at index 0 for each array within $old_array. Can also be using with associative arrays.
use :
public function remove_level($array) {
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $value);
}
}
return $result;
}
which will return second level array values in the same order of the original array.
or you can use array_walk
$results = array();
array_walk($array, function($v, $k) use($key, &$val){
array_merge($results, $v);
});
Below code will also achieve the same result.
$resultArray = array_map('current',$inputArray);
OR
$resultArray = array_map('array_pop',$inputArray);
Note: I have ignored OP's expected result keys. Because it is not possible to have the same keys in the array. The last key will replace the previous one if the same.
foreach($array as $key=>$val) {
$newarr[$val] = $array[$key][$val];
}
untested!
Check this out this is what expected result
<?php
$arrData = array(
"5" => array
(
"8" => "Vit"
),
"6" => array
(
"7" => "Guld"
)
);
foreach($arrData as $key=>$value):
foreach($value as $k=>$v):
$data[$k] = implode(',',$arrData[$key]);
endforeach;
endforeach;
print_r($data);
?>

Categories