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 ';
}
}
Related
i have some problem.
i just want my loop to run, but when i try to do it, it fails, it has to increment each letter by a few, but it doesn't take any new letters at all, why is this happening and what is the reason? in c ++ such code would work.
function accum('ZpglnRxqenU') {
// your code
$result = '';
$letters_result = '';
$letter_original = '';
$num_if_str = strlen($s);
$j = 0;
for ( $i=0; $i <= $num_if_str; $i++ )
{
$letter_original = substr($s, $i, $i+1);
$j = 0;
while($j == $i)
{
$letters_result = $letters_result . $letter_original;
$j++;
}
if($i != strlen($s))
{
$letters_result = $letters_result . '-';
}
}
return $letters_result;
}
It returns
- Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu'
Actual : 'Z-----------'
what problem with what PHP code?
There are a number of problems here:
you're using $s but never initialise it
Your call to substr() uses an incorrect value for the length of substring to return
you're inner loop only runs while $i = $j, but you initialise $j to 0 so it will only run when $i is zero, i.e. for the first letter of the string.
There is a simpler way to do this. In PHP you can address individual characters in a string as if they were array elements, so no need for substr()
Further, you can use str_repeat() to generate the repeating strings, and if you store the expanded strings in an array you can join them all with implode().
Lastly, combining ucwords() and strtolower() returns the required case.
Putting it all together we get
<?php
$str = "ZpglnRxqenU";
$output = [];
for ($i = 0;$i<strlen($str);$i++) {
$output[] = str_repeat($str[$i], $i+1);
}
$output = ucwords(strtolower(implode('-',$output)),"-");
echo $output; // Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu
Demo:https://3v4l.org/OoukZ
I don't have much more to add to #TangentiallyPerpendicular's answer as far as critique, other than you've made the classic while($i<=strlen($s)) off-by-one blunder. String bar will have a length of 3, but arrays are zero-indexed [eg: [ 0 => 'b', 1 => 'a', '2' => 'r' ]] so when you hit $i == strlen() at 3, that's an error.
Aside from that your approach, when corrected and made concise, would look like:
function accum($input) {
$result = '';
for ( $i=0, $len=strlen($input); $i < $len; $i++ ) {
$letter = substr($input, $i, 1);
for( $j=0; $j<=$i; $j++ ) {
$result .= $letter;
}
if($i != $len-1) {
$result .= '-';
}
}
return $result;
}
var_dump(accum('ZpglnRxqenU'));
Output:
string(76) "Z-pp-ggg-llll-nnnnn-RRRRRR-xxxxxxx-qqqqqqqq-eeeeeeeee-nnnnnnnnnn-UUUUUUUUUUU"
Also keep in mind that functions have their own isolated variable scope, so you don't need to namespace variables like $letters_foo which can make your code a bit confusing to the eye.
So I have an array:
$array = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
Obviously they're indexed 0-6.
I want to feed in a specific key index, and then reorder the array, beginning with that key, then going through the rest in the same order, like so:
print_r(somefunction(3, $array));
which would print this:
array
(
'0'=>'Wed',
'1'=>'Thu',
'2'=>'Fri',
'3'=>'Sat',
'4'=>'Sun',
'5'=>'Mon',
'6'=>'Tue'
)
Is there a core function that would do this, or does anyone have a quick solution?
UPDATE
Here's my final function, slightly bigger in scope than my question above, which utilizes AbraCadaver's answer:
public static function ordered_weekdays($format = 'abr')
{
$array = $format == 'full' ? array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') : array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
return array_merge(array_splice($array, get_option('start_of_week'), count($array)-1), $array);
}
Because it's a nice one-liner, I didn't need to make it a separate function.
I've done this before and thought it was simpler than this, but here is what my brain says at the moment:
$index = 3;
$array = array_merge(array_splice($array, $index, count($array)-1), $array);
Try something along these lines...
function reorder($x,$y)
{
$c = count($y);
for ($i=0; $i<$c; $i++)
{
$newArray[$i] = $y[$x];
$x++;
if ($x > $c) $x = 0;
}
return($newArray);
}
function somefunction($n, array $a) {
$x = array_slice($a, 0, $n);
$y = array_slice($a, $n);
return array_merge($y, $x);
}
// forget this: uneccessary looping...
function somefunction($n, array $a) {
for($i = 0; $i < $n; $i++) {
array_push($a, array_shift($a));
}
return $a;
}
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'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++;
}
How would I alter certain elements in the inner for loop if I am using an array with numbers?
e.g
$decryptFields[0] = '1';
$decryptFields[1] = '3';
if($z) == ANY OF THOSE NUMBERS IN THE ARRAY DO SOMETHING.
$x[$i][$z]
so if the inner for loop contains any of those numerals then something will happen e.g maybe I'll make the text bold.
foreach($decryptFields as $dfield) {
echo $dfield;
}
for($i = 0; $i< 10; $i++) {
for($z = 0; $z < $columnLength; $z++) {
echo $x[$i][$z];
}
}
}
Your question is not very clear, but I will do my best to answer it.
If you want to 'do something' if the value $z equals any of the values in the array $decryptFields, you can simply use:
if(in_array($z, $decryptFields)){ /*do something*/}
EDIT: It seems $z is also an array of values.
In that case, use :
$intersection = array_intersect($z, $decryptFields);
foreach($intersection as $key=>$value){
echo "<b>$value</b>";
}
Maybe something like...
for ($i = 0; $i < 10; $i++) {
// Build a string
$str = '';
for ($z = 0; $z < $columnLength; $z++) {
$str .= $x[$i][$z];
}
// If any of the elements of $decryptFields are present in the string, wrap
// it in <span class='bold'></span>
foreach ($decryptFields as $dfield) {
if (strpos($str, $dfield) !== FALSE) {
$str = "<span class='bold'>$str</span>";
break;
}
}
// Echo the result
echo $str;
}
If you need to check multiple items for match to any item of some array, best solution is to build index for the array:
foreach ($decryptFields as $key => $value) $decryptIndex[$value] = $key;
And use that index later:
if (isset($decryptIndex[$x[$i][$z]])) {
// Do something
}
And if you need to get index of matching element in $decryptFields array, use $decryptIndex[$x[$i][$z]]
This is the fastest method, since associative array implementation in PHP is very fast.