I have two arrays:
array(1,2,3,4,5)
array(10,9,8,7,6)
Final array Needed:
array(0=>1:10,1=>2:9,2=>3:8,3=>4:7,4=>5:6)
I can write a custom function which would be quieck enough!! But i wanted to use a existing one so Is there already any function that does this in php? Pass the two input arrays and get the final array result? I read through the array functions but couldn't find any or combination of function that would provide me the result
No built in function but really there is nothing wrong with loop .. Just keep it simple
$c = array();
for($i = 0; $i < count($a); $i ++) {
$c[] = sprintf("%d:%d", $a[$i], $b[$i]);
}
or use array_map
$c = array_map(function ($a,$b) {
return sprintf("%d:%d", $a,$b);
}, $a, $b);
Live Demo
Try this :
$arr1 = array(1,2,3,4,5);
$arr2 = array(10,9,8,7,6);
$res = array_map(null,$arr1,$arr2);
$result = array_map('implode', array_fill(0, count($res), ':'), $res);
echo "<pre>";
print_r($result);
output:
Array
(
[0] => 1:10
[1] => 2:9
[2] => 3:8
[3] => 4:7
[4] => 5:6
)
See: http://php.net/functions
And especially: http://nl3.php.net/manual/en/function.array-combine.php
Also, I don't quite understand the final array result?
Do you mean this:
array (1 = 10, 2 = 9, 3 = 8, 4 = 7, 5 = 6)
Because in that case you'll have to write a custom function which loops through the both arrays and combine item[x] from array 1 with item[x] from array 2.
<?php
$arr1=array(1,2,3,4,5);
$arr2=array(10,9,8,7,6);
for($i=0;$i<count($arr1);$i++){
$newarr[]=$arr1[$i].":".$arr2[$i];
}
print_r($newarr);
?>
Use array_combine
array_combine($array1, $array2)
http://www.php.net/manual/en/function.array-combine.php
Related
I have a php string formed by images and corresponding prices like OK Like
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
I know that if I do:
$myArray = explode(',', $myString);
print_r($myArray);
I will get :
Array
(
[0] => ddb94-b_mgr3043.jpg
[1] => 3800
[2] => 83acc-b_mgr3059.jpg
[3] => 4100
)
But How could I split the string so I can have an associative array of the form?
Array
(
"ddb94-b_mgr3043.jpg" => "3800"
"83acc-b_mgr3059.jpg" => "4100"
)
Easier way to do like below:-
<?php
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$chunks = array_chunk(explode(',', $myString), 2); //chunk array into 2-2 combination
$final_array = array();
foreach($chunks as $chunk){ //iterate over array
$final_array[trim($chunk[0])] = trim($chunk[1]);//make key value pair
}
print_r($final_array); //print final array
Output:-https://eval.in/859757
Here is another approach to achieve this,
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100,test.jpg,12321";
$arr = explode(",",$myString);
$temp = [];
array_walk($arr, function($item,$i) use (&$temp,$arr){
if($i % 2 != 0) // checking for odd values
$temp[$arr[$i-1]] = $item; // key will be even values
});
print_r($temp);
array_walk - Apply a user supplied function to every member of an array
Here is your working demo.
Try this Code... If you will receive all the key and value is equal it will work...
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$myArray = explode(',', $myString);
$how_many = count($myArray)/2;
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $myArray[$i];
$value = $myArray[$i+1];
// store it here
$arra[$key] = $value;
}
print_r($arra);
I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo
We are looking a function that can merge the array keys and values and update it particularly.
$array = array('testing1','testing2','testing3','testing4','testing5','testing6','testing7','testing8','testing9','testing10','testing11','testing12','testing13','testing14');
we just want to merge 10 values with 'space' like this.
$finalarray = array('testing1 testing2 testing3 testing4 testing5 testing6 testing7 testing8 testing9 testing10', 'testing11 testing12 testing13 testing14');
Is there any function that do same thing in PHP ?
you can use array_chunk with array_map
$array = array('testing1','testing2','testing3','testing4','testing5','testing6','testing7','testing8','testing9','testing10','testing11','testing12','testing13','testing14');
$final = array_chunk($array,10);
$final = array_map(function ($n){return implode(" ", $n);}, $final);
Output
array
0 => string 'testing1 testing2 testing3 testing4 testing5 testing6 testing7 testing8 testing9 testing10' (length=90)
1 => string 'testing11 testing12 testing13 testing14' (length=39)
I don't see any direct php function in my mind, but you can try something like this:
$newArray = count($array) > 0 ? array ($array[0]) : array();
for ($i=1;$i<count($array);$i++) {
if ($i % 10 == 0) {
$finalarray[] = $newArray;
$newArray = array ($array[$i]);
} else {
$newArray[] = $array[$i];
}
}
if ( count($newArray) > 0 ) {
$finalarray[] = $newArray;
}
I want to change the value of an array without loop-
Example code:
<?php
//current array
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
//result should be looks like this
$ids = array('1113', '1156', '1342', '1132', '1165');
?>
is it possible to do it without any loop?
Instead of the shown string/array function workarounds, you can also just use a PHP built-in to filter the arrays:
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$ids = array_map("intval", $ids);
This converts each entry into an integer, which is sufficient in this case to get:
Array
(
[0] => 1113
[1] => 1156
[2] => 1342
[3] => 1132
[4] => 1165
)
Try this using array_map():
<?php
function remove_end($n)
{
list($front) = explode("_", $n);
return $front;
}
$a = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$a = array_map("remove_end", $a);
print_r($a);
?>
Demo: http://codepad.org/iGJ3cJW2
Possible? Yes:
$ids[0] = substr($ids[0], 0, -2);
$ids[1] = substr($ids[1], 0, -2);
$ids[2] = substr($ids[2], 0, -3);
$ids[3] = substr($ids[3], 0, -2);
$ids[4] = substr($ids[4], 0, -2);
But why do you want to avoid using a loop in this case?
array_map(), but internally it'd still be using a loop.
function $mycallback($a) {
... process $a
return $fixed_value;
}
$fixed_array = array_map('mycallback', $bad_array);
I have an array which may have duplicate values
$array1 = [value19, value16, value17, value16, value16]
I'm looking for an efficient little PHP function that could accept either an array or a string (whichever makes it easier)
$array2 = ["value1", "value16", "value17"];
or
$string2 = "value1 value16 value17";
and removes each item in array2 or string2 from array1.
The right output for this example would be:
$array1 = [value19]
For those more experienced with PHP, is something like this available in PHP?
you're looking for array_diff
$array1 = array('19','16','17','16','16');
$array2 = array('1','16','17');
print_r(array_diff($array1,$array2));
Array ( [0] => 19 )
For the string version to work, use explode.
Like this:
function arraySubtract($one, $two) {
// If string => convert to array
$two = (is_string($two))? explode(' ',$two) : $two;
$res = array();
foreach (array_diff($one, $two) as $key => $val) {
array_push($res, $val);
}
return $res;
}
This allso returns an array with key = 0....n with no gaps
Test with this:
echo '<pre>';
print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7)));
print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7"));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6")));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6"));
echo '</pre>';