If I have an array that looks like this:
$str = '';
if( $_POST['first'] )
$str = $_POST['first'];
if( $_POST['second'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
if( $_POST['third'] )
$str .= ($str != '' ? ',' : '') . $_POST['third'];
if( $_POST['fourth'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
$str .= ($str != '' ? '.' : '');
Which gives me something like this:
Joe, Adam, Mike.
However, I would like to add an "and" before the last item.
So it would then read:
Joe, Adam, and Mike.
How can I modify my code to do this?
Arrays are awesome for this:
$str = array();
foreach (array('first','second','third','fourth') as $k) {
if (isset($_POST[$k]) && $_POST[$k]) {
$str[] = $_POST[$k];
}
}
$last = array_pop($str);
echo implode(", ", $str) . " and " . $last;
You should probably special case the above for when there's one item. I, in fact, wrote a function called "conjunction" which does the above, and includes the special case:
function conjunction($x, $c="or")
{
if (count($x) <= 1) {
return implode("", $x);
}
$ll = array_pop($x);
return implode(", ", $x) . " $c $ll";
}
Nice question!
Updated: General purpose way to do this:
function and_form_fields($fields)
{
$str = array();
foreach ($fields as $k) {
if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) {
$str[] = $v;
}
}
return conjunction($str, "and");
}
...
and_form_fields(array("Name_1","Name_2",...));
I added correct $_POST checking to avoid notices, and blank values.
The first ideea that comes to my mind is to always keep a last one name in an auxiliar variabile. When you have another one to put in, you take it put the 'comma' and get the next name in the aux.
At the end, when you finished added the names, you add 'and' and the last name from aux.
Instead of posting each as a separate variable, why not post them as an array:
#pull the array from the POST:
$postedarray = $_POST['names'];
#count the number of elements in the posted array:
$numinarray = count($postedarray);
#subtract 1 from the number of elements, because array elements start at 0
$numinarray = $numinarray -1;
#set a prepend string
$prependstr = "and ";
#Pull the last element of the array
$lastname = $postedarray[$numinarray];
#re-define the last element to contan the prepended string
$postedarray[$numinarray] = "$prependstr$lastname";
#format the array for your requested output
$comma_separated = implode(", ", $postedarray);
print "$comma_separated";
Related
I have successfully create conditions which check the array count. Everything I have is working, but I am trying to figure out how to configure it so that if the results are:
1, 2, 3
I want it to be:
1, 2 and 3
How can I do this?
$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count($proposal_type_arr);
if ($proposal_type_count == 1) {
$proposal_type = implode("", $proposal_type_arr);
}
else if ($proposal_type_count == 2) {
$proposal_type = implode(" and ", $proposal_type_arr);
}
else if ($proposal_type_count > 2) {
$proposal_type = implode(", ", $proposal_type_arr);
}
You could use array_pop() to grab the last element in the array. When combined with implode() you'd be able to cut down on the conditional logic.
Example:
$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count( $proposal_type_arr );
if ( $proposal_type_count > 1 ) {
$last_el = array_pop( $proposal_type_arr );
$proposal_type = implode( ', ', $proposal_type_arr ) . ' and ' . $last_el;
} else {
$proposal_type = current( $proposal_type_arr );
}
You can do it like this.
Try this code snippet here sample array taken
elseif ($proposal_type_count > 2)
{
$temp=$proposal_type_arr[$proposal_type_count-1];//getting last element
unset($proposal_type_arr[$proposal_type_count-1]);//unsetting last element
$proposal_type = implode(", ", $proposal_type_arr);
echo $proposal_type.= " and $temp";//attaching last element with "and "
}
You can use array_pop to pop the last element out, and if you want to just keep the first two, use array_slice(). Then use implode to trans array to string.
$end = array_pop(&$array);
echo implode(',', $array) . ' and ' . $end;
Before I got this answer
preg_replace("~(?<=$str&&).*~", '7', $str);
which is good but what if within the array I have a similar string mary&&5 and rosemary&&5 and I stricktly want to change only mary&&5 and not disturb the other array, is it posible? and how?
The question before was:
`$array = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8", etc..);`
and I know only the string before && which is username. $str = "mary&&"; Note that I don't know what is after &&
I want to know whether exist or not within the array, and if exist change the value to something new like mary&&7
`$isExists = preg_replace("some","some", $array);
if ($isExists){
echo "Its exists";
} else {
echo "Not exixts"
} ;`
How can I change the portion of the value after && in mary&&5 or completely change mary&&5 to mary&&7 since I don't know before hand the value mary&&5?
Thanks for your answer :)
`$name = "mary";
$res = "7";
$str = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8","rosemary&&5");
for ($i = 0; $i < count($str); ++$i) {
$r = preg_replace("~(?<=$name).*~",$res, $str);}`
$arr = array('josh&&3', 'mary&&5', 'cape&&4', 'doggy&&8', 'rosemary&&5');
$name = 'mary';
$number = '7';
$replacement = $name . '&&' . $number;
So, a way without regex:
foreach($arr as $k=>$v) {
if (explode('&&', $v)[0] === $name)
$arr[$k] = $replacement;
}
( or you can use strpos($v, $name . '&&') === 0 as condition)
a way with regex:
$arr = preg_filter('~\A' . $name . '&&\K.*~', $number, $arr);
(where \K removes all on the left from the match result, so the name and && aren't replaced)
I am trying to use a FOREACH loop in PHP to output different messages depending on the position of the value in the array. My code is below:
$qtyValidFiles = count($validFiles);
$tick = 0;
foreach($validFiles AS $validItem)
{
if($tick = 0)
{
echo"'#$validItem,";
}
elseif($tick < $qtyValidFiles -1 && $tick != 0)
{
echo"#$validItem,";
}
elseif($tick = $qtyValidFiles -1)
{
echo"#$validItem'";
}
}; $tick++;
In this instance, $qtyValidFiles has 4 values.
The code above returns:
#Games'#Movies'#Music'#TV'
which suggests to me that $tick is always being seen as value 3.
If $validFiles is an indexed array, you can do:
foreach ($validFiles as $tick => $validItem)
instead of incrementing $tick yourself.
Your entire loop is unnecessary, though. You can do:
echo "'" . implode(",", array_map(function($x) { return "#$x"; }, $validFiles)) . "'";
This should be better than your code because you don't do the right thing if the array has exactly 1 item; you'll print the beginning quote and a comma, but I think you really want the one element surrounded by quotes.
$tick is always 0 because the $tick++; is outside of the loop. Move it up a line.
Also as Rahul Kumar states, use == as the comparison operator.
Or just do this, no loop needed:
echo '#' . implode(',#', $validFiles);
Seems like the simpler and correct equivalent to your code would be this:
$qtyValidFiles = count($validFiles);
$str = '';
foreach($validFiles AS $validItem) {
$str .= "#$validItem,";
}
if (!empty($str)) {
echo "'" . substr($str, 0, -1) . "'"; //removes the last ","
}
I've been trying to get this to work and while I have tried many methods posted on this site on other pages, I can't get any of them to work.
I need to identify the last key so that my results don't have a , at the end. This sounds like such and easy task but I just cant seem to get it to work! At this point I'm guessing I've just had a typo or something that I overlooked. Any help would be greatly appreciated.
This is what I have:
<?php
$searchString = $_GET["s"];
$prefix = 'http://link_to_my_xml_file.xml?q=';
$suffix = '&resultsPerPage=100';
$file = $prefix . $searchString . $suffix;
if(!$xml = simplexml_load_file($file))
exit('False'.$file);
foreach($xml->results->result as $item) {
echo $item->sku . ",";
}
?>
Now this works just fine, it just has a , at the end:
12345,23456,34567,45678,
For reference my xml file is laid out like: results->result->sku, but with a lot more mixed in. I'm just singling out the fields.
Consider identifying the first instead?
$first = true;
foreach($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ',';
}
echo $item->sku;
}
Use rtrim()
foreach($xml->results->result as $item) {
$mystr .= $item->sku . ",";
}
echo rtrim($mystr, ",")
Should output:
12345,23456,34567,45678
Demo!
If your keys are in numerical order like: 0, 1, 2, 3 etc this could be a solution:
foreach($xml->results->result as $key => $item)
{
if( $key > 0 ) echo ", ";
echo $item->sku
}
Possible solution #1:
$first = true;
foreach ($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ', ';
}
echo $item->sku;
}
Possible solution #2:
$items = array();
foreach ($xml->results->result as $item) {
$items[] = $item->sku;
}
echo join(', ', $items);
You can just put everything in a string and then run:
substr($yourstr, 0, -1);
on your code to remove the last character:
http://de1.php.net/manual/en/function.substr.php
Or get the total number of entries in your array and count your position
i'm still quite new to programming, so please excuse me.
I need to do the following:
Right now i have a string being output with two value: one with characters and numbers, a comma and the second with just a boolean value.
9fjrie93, 1
I would like to trim the string so it just ourputs as the boolean value. e.g.
1
I then need to perform an equality check on the boolean value. If it's 1 do one thing, else do something else. Would a simple if statement suffuce?
Thanks very much
No need for explode if it's always the last character.
<?php
$val = '9fjrie93, 1';
if( substr( $val, -1 ) === '1' ) {
// do stuff.
}
else {
// do stuff. Just other stuff.
}
How about:
$vals = explode(", ", "9fjrie93, 1");
if ($vals[1]) ...
You can also use list to name the results returned:
$original_str = '9fjrie93, 1';
list($characters, $boolean) = explode(', ', $original_str);
echo $boolean;
Try this:
$str = '9fjrie93, 1';
$str = explode(', ', $str); //it returns array('9fjrie93', '1')
$str = end($str); //takes the last element of the array
$mystring = '9fjrie93, 1';
$findme = ',';
$pos = strpos($mystring, $findme);
$i= substr($mystring,$pos);
$string = "9fjrie93, 1";
$val = substr($string, (strrpos($string, ',')+1));
Don't use explode since it's slower
If the 1 is always at the end of the line, you can do:
$line = '9fjrie93, 1'
if ( $line[strlen([$line])-1] == '1' ) {
// do stuff
} else {
// do other stuff
}
Which should at least perform better than explode, str_replace and substr solutions.
$pos = strpos($source_str, ',');
substr($source_str, $x_pos + 1);
hope this will solve it.
$output = str_replace(',', '', strstr('9fjrie93, 1', ','));
if( $output == '1' ) {
....do something
} else {
...do something else
}