I'll let the code speak:
$params = array();
$qtyCount = count(array(1,2,3,4,5));
$qtyAr = array(6,7,8,9,10);
$i = 1;
while($i <= $qtyCount){
$params['quantity_'.$i] .= $qtyAr[$i];
$i++;
}
But when I do this, the last value is missing.
BTW: the values in the qtyCount and qtyAr are bugus... just for example.
I would opt for a simpler approach:
array_walk($qtyAr, function($item, $index) use (&$params) {
$key = sprintf("quantity_%u", $index);
$params[$key] = $item;
});
It appears that you are starting at the wrong index (1), $i should be = 0 as others have pointed out.
You're missing the last element because your unasssociated array starts with 0 and your loop starts with 1. This is why foreach works so much better because it iterates over ALL your elements.
$qtyAr = array(6,7,8,9,10);
$i = 1;
foreach($qtyAr as $val) {
$params['quantity_' . $i] = $val;
$i++;
}
Related
I have the following array:
$alphabet = array("a","b","c","d","e","f","g")
If I wanted to begin from "d" and loop through the array to be outputted as d,e,f,g,a,b,c.
How can this be achieved?
<?php
$alphabet = array("a","b","c","d","e","f","g");
$startIndex = 3;// index of d
$count = count($alphabet);
for($x = 0; $x < count($alphabet); $x++){
$index = $x + $startIndex < $count ? $x + $startIndex : $x + $startIndex - $count;
echo $alphabet[$index];
}
outputs
defgabc
see live demo
if you don't know the index of the element you want you can use array_search
$startIndex = array_search('d', $alphabet);
You can try to use array_slice function to achieve what you want:
<?php
$alphabet = array("a","b","c","d","e","f","g");
// find the index of the start element in the original array
$index = array_search("d", $alphabet);
// iterate the array from starting point to the end
foreach (array_slice($alphabet, $index) as $value) {
echo $value, ",";
}
// iterate the array from the very beginning to the starting point
foreach (array_slice($alphabet, 0, $index) as $value) {
echo $value, ",";
}
I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!'); // these is my input
//i want output like
array('Hello World!','Beautiful Day!');
The generic solution would be something like this:
$result = array_map(function($pair) {
return join(' ', $pair);
}, array_chunk($arr, 2));
It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.
Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);
A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
if (isset($arr[$i+1])) {
$result[] = $arr[$i] . ' ' . $arr[$i+1];
}
else {
$result[] = $arr[$i];
}
}
In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
if (($i++) % 2==0)
$arr[]=$v.' ';
else {
$arr[count($arr)-1].=$v;
}
}
Live: http://ideone.com/VUixMS
Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
$out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);
Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
$result[] = $value . " " . $arr[$key + 1];
}
}
print_r($result);
A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);
I have an array of strings of random letters, and I need to know which letters are consistent between the array members. The count of the letters are important.
My method right now is loop through the array, doing a split, then looping through the spitted string to count the occurrences of each letter, then update the array with letter => count
Then do an array_reduce that creates a new array of members who only occur in all arrays. But, it's not working.
<?
$a[] = "emaijuqqrauw";
$a[] = "aaeggimqruuz";
$a[] = "aabimqrtuuzw";
$a[] = "aacikmqruuxz";
$a[] = "aacikmqruuxz";
$a[] = "aaciimqruuxy";
foreach($a as $b){
$n = str_split($b, 1);
foreach($n as $z){
$arr[$z] = substr_count($b, $z);
}
ksort($arr);
$array[] = $arr;
unset($arr);
}
$n = array_reduce($array, function($result, $item){
if($result === null){
return $item;
}else{
foreach($item as $key => $val){
if(isset($result[$key])){
$new[$key] = $val;
}
}
return $new;
}
});
foreach($n as $key => $val){
echo str_repeat($key, $val);
}
This returns aaiimqruu - which is kinda right, but there's only 2 i's in the last element of the array. There's only one i in the rest. I'm not sure how to break that down farther and get it to return aaimqruu- which I'll then pop into a SQL query to find a matching word, aquarium
There's array_intersect(), which is most likely what you'd want. Given your $a array, you'd do something like:
$a = array(.... your array...);
$cnt = count($a);
for($i = 0; $i < $cnt; $i++) {
$a[$i] = explode('', $a[$i]); // split each string into array of letters
}
$common = $a[0]; // save the first element
for($i = 1; $i < $cnt; $i++) {
$common = array_intersect($common, $a[$i]);
}
var_dump($common);
How about you do it this way? Finds out the occurrence of an item throughout the array.
function findDuplicate($string, $array) {
$count = 0;
foreach($array as $item) {
$pieces = str_split($item);
$pcount= array_count_values($pieces);
if(isset($pcount[$string])) {
$count += $pcount[$string];
}
}
return $count;
}
echo findDuplicate("a",$a);
Tested :)
Gives 12, using your array, which is correct.
Update
My solution above already had your answer
$pieces = str_split($item);
$pcount= array_count_values($pieces);
//$pcount contains, every count like [a] => 2
Seems like array_reduce is the best function for what this purpose, however I just didn't think of adding a conditional to give me the desired effect.
$new[$key] = ($result[$key] > $val) ? $val : $result[$key];
to replace
$new[$key] = $val;
did the trick.
I have two arrays in my code.
Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2)
or something else?
If they both the same keys, you can do this:
foreach($array1 as $key=>data1){
$data2 = $array2[$key];
}
Assuming both have the same number of elements
If they both are 0-indexed arrays:
foreach ($array_1 as $key => $data_1) {
$data_2 = $array_2[$key];
}
Otherwise:
$keys = array_combine(array_keys($array_1), array_keys($array_2));
foreach ($keys as $key_1 => $key_2) {
$data_1 = $array_1[$key_1];
$data_2 = $array_2[$key_2];
}
Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.
Are both arrays the same size always?
Then this will work:
$max =sizeof($array);
for($i = 0; $i < $max; $i++)
array[$i].attribute
array2[$i].attribute
If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.
iterative methods:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/control-structures.do.while.php
use for or while loop e.g.
$i = 0;
while($i < count($ar1) && $i < count($ar2) ) // $i less than both length !
{
$ar1Item = $ar1[$i];
$ar2Item = $ar2[$i];
$i++;
}
No to my knowledge with foreach, but can be easily done with for:
<?php
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
for ($i=0;$cond1 || $cond2;$i++)
{
if ($cond1)
{
// work with $array1
}
if ($cond2)
{
// work with $array2
}
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
}
?>
I have an array and I'd like to add a string to each item in the array, apart from the last item.
Any ideas how I'd do this?
Thanks
This should do it for both numerically-indexed arrays and associative arrays:
$i = 0;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ < $c - 1) {
$array[$key] .= 'string';
}
}
If your array is numerically indexed, a simple loop does the job.
for ($i = count($array) - 2; $i >= 0; $i--) {
$array[$i] = $array[$i] . $stringToAppend;
}
I don't think there is a native command for this.
Just do it the traditional way.
// Your array.
$MyArray = array("Item1","Item2","Item3");
// Check that we have more than one element
if (count($MyArray) > 1) {
for ($n=0; $n<count($MyArray)-1; $n++) {
$MyArray[$n] .= " Appended string";
}
}
The code is from the top of my head, so maybe some tweeking might do he trick.
Well a simple for loop would be the obvious thing I guess.
for ( $i=0; $i < count( $myArray )-1; $i++ )
{
$myArray[$i] = "Hey look a string";
}
But then you might also just use array_fill to do a similar job:
array_fill( 0, $sizeOfArray, "Hey look a string" )
Then you can just set the last value to be whatever you want it to be.
EDIT: If by "add a string to each item" you mean you already have a value in the array and you want to append a string, then I would use my first suggestion with $myArray[$i] .= "Hey look a string"; instead of the simple assignment.
$array =array();
$statement = null;
for ($j= 0;$j<count($array);$j++) {
if ($j === count($array)-1) {
$statement .= $array[$j];
} else {
$statement .= $array[$j].' OR ';
}
}