PHP add an item from an array - php

Let's say i have this array:
$array = (1,2,4,5);
Now how do i add missing 3 in above array in the correct position index/key-wise?

Try:
array_splice($array, 2 /*offset*/, 0 /*length*/, 3 /*value*/);
Note that this will reorder the input array's keys from 0 to n-1.
(Edit: The return value is not used in this case.)

array_merge(array_slice($array,0,2),array(3),array_slice($array,2))

Maybe I'm missing the complexity of your question, but doesn't the following give you what you want?
$array[] = 3;
sort($array);

Last but not least:
Append new stuff at the end of the array
Sort the array when you finally need it: asort()

function insertMissingIntoArray($values = array(), $valueIncrement = 1) {
$lastValue = 0;
foreach ($values as $key=>$val) {
if ($key != 0) {
if ($val != $lastValue + $valueIncrement) {
array_splice($values, $key, 0, $val);
}
$lastValue = $val;
}
}
return $values;
}
Used like this:
$values = array(1,2,4,5,7,9);
$fixedValues = insertMissingIntoArray($values, 1);
// $fixedValues now is (1,2,3,4,5,6,7,8,9)

function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
usage:
array_insert($a,2,3);

Related

Optimize multidimensional array creation

I have a list of array keys and nesting level in one array, for example:
$keys[0] = 'first';
$keys[1] = 'second';
$keys[2] = 'third';
How can I transform this into a multidimensional array in the following format:
$array['first']['second']['third'] = 'value';
I tried a couple different variations that did not work out and the keys overwrote themselves. The simplest way is to get a count of the number of keys and manually cover each scenario but this is hardly optimized and does not dynamically grow.
$keyLen = count($keys);
if ($keyLen == 1) {
$array[$keys[0]] = 'value;
} elseif ($keyLen == 2) {
$array[$keys[0]][$keys[1]] = 'value;
} elseif ($keyLen == 3) {
$array[$keys[0]][$keys[1]][$keys[2]] = 'value';
} ...
A couple notes, the value is not of significance it's the nesting of the array keys, and I cannot change the initial array format.
You could go backwards through your input array and wrap the previous result as you go:
$nested = 'value';
for (end($keys); key($keys)!==null; prev($keys)){
$nested = [current($keys) => $nested];
}
At the end $nested will have the desired structure.
Give this a try. Here we're using references to stack our new arrays.
<?php
$keys = array('first', 'second', 'third');
$array = array();
$current = &$array;
foreach($keys as $key => $value) {
$current[$value] = array();
$current = &$current[$value];
}
$current = 'Hello world!';
print_r($array);
Starting from the last Item you can loop through the array, pop the last one and build the new array:
<?php
$keys[0] = 'first';
$keys[1] = 'second';
$keys[2] = 'third';
function createKey($array) {
$b = "value";
while(count($array)>0) {
$key = array_pop($array);
$b = [$key => $b];
}
return $b;
}
var_dump(createKey($keys));
// Output:
array(1) {
["first"]=>
array(1) {
["second"]=>
array(1) {
["third"]=>
string(5) "value"
}
}
}
Another option is to loop the reversed keys and wrap the previous result:
$array = [];
foreach(array_reverse($keys) as $key) {
$temp = $array;
unset($array[key($array)]);
$array[$key] = $temp;
}
Then you could set your value:
$array['first']['second']['third'] = 'value';
Demo
You could even eval this in a safe way without leaking any input data into the eval-string:
$value = 'value';
eval( '$array[$keys['. implode(']][$keys[', range(0, count($keys)-1)) . ']] = $value;' );
or with an additional counter even simpler and shorter:
$value = 'value';
$i = 0;
eval( '$array' . str_repeat('[$keys[$i++]]', count($keys)) . ' = $value;' );

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];
}
}

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

Filter or Sorting multidimensional arrays in PHP

If i have two array as following:
$array1 = array(array('id'=>11,'name'=>'Name1'),array('id'=>22,'name'=>'Name2'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'),array('id'=>55,'name'=>'Name5'));
$array2 = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'));
My expect result, the array2 should be always at the beginning :
$newarray = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'), array('id'=>11,'name'=>'Name1'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'));
My current solution is using two for loops:
foreach($array2 as $Key2 => $Value2) {
foreach($array1 as $Key1 => $Value1){
if($Value1['id'] != $Value2['id']) {
//push array
}
}
}
Edit:
The result "$newarray" should not include the duplicate ids from array1.
But i am looking for a faster and simpler solution.
SOLUTION:
$a1 = array();
foreach ($array1 as $v) $a1[$v['uuid']] = $v;
$a2 = array();
foreach ($array2 as $v) $a2[$v['uuid']] = $v;
$filtered = array_values(array_diff_key($a1, $a2));
//print_r($filtered);
$newarray = array_merge($array2, $filtered);
Thank you guys!!!!
Thanks.
Regards Jack
you want $new_array = array_merge($array2, $array1); puts the second array onto the end of the first one
You can use array_merge() function for that, like this:
$newarray = array_merge($array2, $array1);
I am not sure about your requirement but to sort multi-dimensional array on some specific key
You need to use usort function
Try the code below:
$cmp = function ($a, $b){
$a_val = $a['id'];
$b_val = $b['id'];
if ( $a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
};
usort($array2,$cmp);
$array2 will be sorted by 'id'

Merge every other array php

array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?
You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.
Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}
This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO
if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help
Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);

Categories