PHP array keys as nth value - php

I have an Associative array as
$array = Array([0]=>a[1]=>b[2]=c[3]=>d);
I need to build an array from this array where the the first key becomes a and the value becomes b & 2nd key becomes c and value becomes d.
Output should be:
$finalarray = Array([a]=>b,[c]=>d);
I have tried this following code:
foreach($array as $key=>$value){
$arr[$value] = array_slice($array, 1, 1);
$finalarray[] = $arr;
}
Please help me with this!

The best way is to loop on your first array, but to skip one value on two:
$array = array("a", "b", "c", "d");
$finalArray = array();
for ($i = 0; $i < count($array); $i+=2) {
$finalArray[$array[$i]] = $array[$i + 1];
}

This may help:
$a = array('a','b','c','d'); $b = array();
$length = count(a)%2 ? count($a)-1 : count($a);
for($i=0; $i<$length; $i++){
$b[$a[$i]] = $a[++$i];
}
var_dump($a,$b);

Little changed your code:
$i=0;
foreach($array as $key=>$value){
$value_2=$value++;
if($i%2==0)
$arr[$value_2] =$value;
$i++;
//$finalarray[] = $arr;
}
echo"<pre>";
print_r($arr);

If your array is associative , below code may help you
<?php
$array = array(0=>'a',1=>'b',2=>'c',3=>'d');
$new_array = array();
for($i=0;$i<count($array);$i+=2)
{
$new_array[$array[$i]] = $array[$i+1];
}
print_r($new_array);
?>

Related

How to combine three arrays without using array_merge or array_combine in php

I want to combine three arrays into one
I am expecting like output are using array_combine or array_merge
Likes
friends,
usa,
usa2,
..,
..,
so.on..,
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = $array1+$array2+$array3;
echo "<pre>";
print_r($output);
echo "</pre>";
But here i am getting output as
likes,
friends,
USA
In PHP 5.6+ You can also use ... when calling functions to unpack an array or
Traversable variable or literal into the argument list:
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";
demo
check this out custom function for array push
<?php
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
function push($array1,$array2){
$return = array();
foreach($array1 as $key => $value){
$return[] = $value;
}
foreach($array2 as $key => $value){
$return[] = $value;
}
return $return;
}
$array = push($array1,$array2);
$array = push($array,$array3);
print_r($array);
If you want to have an array of arrays, each element at a given index having the values of the three arrays at the respecting index, then:
$length = count($array1);
$result = array();
for ($index = 0; $index < $length; $index++) {
$result[]=array($array1[$index], $array2[$index], $array3[$index]);
}
If you simply want to put all items into a new array, then:
$result = array();
for ($index = 0; $index < count($array1); $index++) {
$result[]=$array1[$index];
}
for ($index = 0; $index < count($array2); $index++) {
$result[]=$array2[$index];
}
for ($index = 0; $index < count($array3); $index++) {
$result[]=$array3[$index];
}
Use Array Merge
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = array_merge($array1,$array2,$array3);
echo "<pre>";
print_r($output);
echo "</pre>";

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

PHP combines 2 arrays

I have 2 arrays in php
$array1[] = a,b,c,d,e;
$array2[] = 1,2,3,4,5;
$data = array('letter'=>$array1,'num'=>$array2);
return json_encode($data);
This will return:
[[a,b,c,d,e],[1,2,3,4,5]]
I'd like to return it in json_encode like this:
$data = [[1a,1],[b,2],[c,3],[d,4],[e,5]];
Can someone help me with this?
this is the simplest solution
$result = array();
foreach ($array1 as $k1 => $v1) {
$result[] = array($v1, $array2[$k1]);
}
echo json_encode($result)
but arrays must have the same length and same keys
Try below code, it is flexible and don't have to care about the length of the arrays.
<?php
$letters = array('a','b','c','d','e');
$numbers = array('1','2','3','4','5');
$counter = (sizeof($letters) > sizeof($numbers)) ? sizeof($letters) : sizeof($numbers);
$arr = array();
for($i=0; $i<$counter; $i++)
{
if(array_key_exists($i, $letters))
$arr[$i][] = $letters[$i];
if(array_key_exists($i, $numbers))
$arr[$i][] = $numbers[$i];
}
$json = json_encode($arr);
echo $json;
Output:
[["a","1"],["b","2"],["c","3"],["d","4"],["e","5"]]
Demo:
http://3v4l.org/7v7X4
What you are looking for is the function array_combine().
Here is an example:
$array1 = array("a","b","c","d","e");
$array2 = array(1,2,3,4,5);
$data = array_combine($array1, $array2);
$new_data = array();
foreach($data AS $key => $value) {
$new_data[] = array($key, $value);
}
print_r(json_encode($new_data));
Which should return something like:
[["a",1],["b",2],["c",3],["d",4],["e",5]]
UPDATE Changed the code to give the result wanted...

Dynamically populate php array using foreach loop

How can I implement the code:
$numberList3 = array();
for($i = 0; $i < 10; $i++)
{
$numberList3[$i] = $i;
}
print_r($numberList3);
Using a foreach loop as the no. of times the loop is going to execute is decided by the user at run time.
Any suggestion.?
Use array_fill maybe?
<?php
$n = 10;
$arr = array_fill(0,$n,0);
foreach($arr as $k => $v) {
$arr[$k] = $k;
}
print_r($arr);
Or, as suggested by #deceze, use range
<?php
$n = 10;
$arr = array();
foreach(range(0,$n-1) as $v) {
$arr[$v] = $v;
}
print_r($arr);
Or when the value is the same as the key, you can use just this:
<?php
$n = 10;
$arr = range(0,$n-1);
// no foreach needed
print_r($arr);
foreach() works for object and array not for a single value.
What you can do create an array or object from users input.
like:
$userInput = 10;
$forEachArray = array_fill(0, $userInput, 0);
$arrayToDisplay = array();
foreach($forEachArray as $key){
$arrayToDisplay[$key] = $key;
}
print_r($arrayToDisplay);

PHP: Transformation of array

There is the following array:
arr1 = array(array('xxx',3),array('yyy',2));
I need to transform it into the array arr2, where the number of occurrence of each entry is equal to the 2nd column value in array arr1. For instance, for the above given arr1, arr2 should be the following:
arr2 = array(array('xxx'),array('xxx'),array('xxx'),array('yyy'),array('yyy'));
I wrote the following code, but my question is: Is it possible to do the same in a simpler way?
for ($i=0; $i<count($arr1); $i++) {
for ($j=0; $j<$arr1[i][1]; $j++) {
$arr2[] = array($arr1[0]);
}
}
I think a foreach is simpler and easier to read.
$arr1 = array(array('xxx', 3), array('yyy', 2));
$arr2 = array();
foreach ($arr1 as $arr)
{
for ($i = 0; $i < $arr[1]; $i++)
{
$arr2[] = array($arr[0]);
}
}
foreach ($arr1 as $entry) {
$arr2[] = array_fill(0, $entry[1], array($entry[0]));
}
$arr2 = call_user_func_array('array_merge', $arr2);
I wouldn't use it though. It's much less readable.

Categories