Assuming a list like this:
$array = array('item1', 'item2', 'item3'); // etc...
I would like to create a comma separated list like so:
implode(',', $array);
But have the added complication that I'd like to use the following logic: if the item index is a multiple of 10, use ',<br>' instead of just ',' for the separator in the implode() function.
What's the best way to do this with PHP?
I did this like so, but wonder if there's a more concise way?
function getInventory($array, $title) {
$list = array();
$length = count($array);
$i = 1;
foreach($array as $item) {
$quantity = $item[1];
if(!$quantity)
$quantity = 1;
$item_text = $quantity . $item[3];
if($i > 9 && ($i % 10) == 0) {
$item_text .= ',<br>';
} elseif($i !== $length) {
$item_text .= ',';
}
$list[] = $item_text;
$i++;
}
$list = implode('', $list);
$inventory = $title . $list . '<br>';
return $inventory;
}
This solution will work if you want to use the <br> whenever the key is divisible by 10.
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, array_keys($array)));
If instead you want every 10th element and not just the element where the key is divisible by 10, use this:
implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, range(1, count($array)));
Thanks to #Jacob for this possibility.
We keep the , for the implode function and variably adjust the input array values to be prepended with a <br>.
$k%10 uses the modulus operator to return the remainder for $k divided by 10 which will be 0 when $k is a multiple of 10.
As long as it's not the actual array keys that you're concerned about but the position in the array (ie. the break is on every tenth element rather than every index that is a multiple of ten), then you can do it this way:
$foo = array();
for($n = 0; $n < 54; $n++) $foo[] = $n;
$parts = array_chunk($foo, 10);
for($n = 0; $n < count($parts); $n++){
echo implode(',', $parts[$n]);
if($n < count($parts) - 1) echo ',';
echo "<br/>\n";
}
$str = '';
$array = ....;
$i = 0;
foreach($array as $index)
$str .= $array[$index].' ,'.($index % 10 ? ' ' : '<br/>');
$str = substr($str, 0, strlen($str) - 2); // trim the last two characters ', '
Related
i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>
What I need to add to this script to get 3 longest words from string?
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$max = $arr[0];
for ($i = 0; $i < count($arr); $i++) {
if (strlen($arr[$i]) > strlen($max)) {
$max = $arr[$i];
}
}
echo $max;
?>
Please help to modify the script. We have to not use the usort function.
The solution would be like this:
Use explode() to get the words of the string in an array
"Partially" sort the array elements in descending order of length
Use a simple for loop to print the longest three words from the array.
So your code should be like this:
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$count = count($arr);
for($i=0; $i < $count; $i++){
$max = $arr[$i];
$index = $i;
for($j = $i + 1; $j < $count; ++$j){
if(strlen($arr[$j]) > strlen($max)){
$max = $arr[$j];
$index = $j;
}
}
$tmp = $arr[$index];
$arr[$index] = $arr[$i];
$arr[$i] = $tmp;
if($i == 3) break;
}
// print the longest three words
for($i=0; $i < 3; $i++){
echo $arr[$i] . '<br />';
}
Alternative method: (Using predefined functions)
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr,function($a, $b){
return strlen($b)-strlen($a);
});
$longest_string_array = array_slice($arr, 0, 3);
// display $longest_string_array
var_dump($longest_string_array);
You need to create your own comparative function and pass it with array to usort php function.
Ex.:
<?php
function lengthBaseSort($first, $second) {
return strlen($first) > strlen($second) ? -1 : 1;
}
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr, 'lengthBaseSort');
var_dump(array_slice($arr, 0, 3));
It will output 3 longest words from your statement.
According to author changes:
If you have no ability to use usort for some reasons (may be for school more useful a recursive function) use following code:
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
function findLongest($inputArray) {
$currentIndex = 0;
$currentMax = $inputArray[$currentIndex];
foreach ($inputArray as $key => $value) {
if(strlen($value) > strlen($currentMax)){
$currentMax = $value;
$currentIndex = $key;
}
}
return [$currentIndex, $currentMax];
}
for($i = 0; $i < 3; $i++) {
$result = findLongest($arr);
unset($arr[$result[0]]);
var_dump($result[1]);
}
?>
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'm using the below code to separate odd and even and store it in different variable. When there are only 2 value available then it works fine but when the number value increases then it doesn't. I want to make it dynamic so that n number of values can be separated and stored correctly.
Example:
If the value of
$final_array = "PNL testing 1,10,PNL testing 2,35,";
It prints nicely:
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
But when it increases from
$final_array = "PNL testing 1,10,PNL testing 2,35,";
to
$final_array = "PNL testing 1,10,PNL testing 2,35,Team 3,95,";
Then also it prints
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
Please guide me through on where I am going wrong.
$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $final_array, $res);
$teams = join(', ', $res[1]); //will display teams
$amount = join(', ', $res[2]); //will display amount every team have
echo $teams . "<br />" . $amount;
I think you can totally drop the REGEX in favor of good old explode/implode with some logic in it:
$teams = array();
$amount = array();
$a = explode(',', trim(trim($final_array), ','));
foreach ($a as $i => $v)
if (($i % 2) == 0) $teams[] = trim($a);
else $amount[] = trim($a);
$teams = implode(', ', $teams);
$amount = impode(', ', $amount);
In the above code $tms and $amn are temporary arrays. In the foreach we take the exploded values from the string and we store them in those two arrays sorting them by key (if it's even then it's a team otherwise it's an amount).
At the end we just implode the new values into your output variables $teams and $amount.
It will much easier I think to use explode:
$result = explode(',', $final_array);
$teams = array();
$amount = array();
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
$teams = implode(', ', $teams); //will display teams
$amount = implode(', ', $amount); //will display amount every team have
echo $teams."<br />".$amount;
I would change this part of Michal Trojanowski for more efficiency
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
you see it has an extra condition we can remove it by like this
$length = count($result);//cache count result
for ($i = 0; $i < $length; $i += 2) {
$teams[] = $result[$i];
}
for ($i = 1; $i < $length; $i += 2) {
$amount[] = $result[$i];
}
Here the loop is running same but it just removes the the condition.
How I cut the extra 0 string from those sample.
current string: 0102000306
required string: 12036
Here a 0 value have in front of each number. So, i need to cut the extra all zero[0] value from the string and get my expected string. It’s cannot possible using str_replace. Because then all the zero will be replaced. So, how do I do it?
Using a regex:
$result = preg_replace('#0(.)#', '\\1', '0102000306');
Result:
"12036"
Using array_reduce:
$string = array_reduce(str_split('0102000306', 2), function($v, $w) { return $v.$w[1]; });
Or array_map+implode:
implode('',array_map('intval',str_split('0102000306',2)));
$currentString = '0102000306';
$length = strlen($currentString);
$newString = '';
for ($i = 0; $i < $length; $i++) {
if (($i % 2) == 1) {
$newString .= $currentString{$i};
}
}
or
$currentString = '0102000306';
$tempArray = str_split($currentString,2);
$newString = '';
foreach($tempArray as $val) {
$newString .= substr($val,-1);
}
It's not particularly elegant but this should do what you want:
$old = '0102000306';
$new = '';
for ($i = 0; $i < strlen($old); $i += 2) {
$new .= $old[$i+1];
}
echo $new;