Getting rid of the last comma from the php foreach loop - php

I'm retrieving this value from single block of the table i.e,
sample1,sample2,sample3,
I dont want the last comma to be retrieved as my output is creating an empty result at the end. Here's my code:
$imageExtractExplode = explode(",", $imageExtract);
foreach
($imageExtractExplode as $imageExtractFinal){
//my echo code
}
How do i stop the last comma from getting displayed

Can you try this, You can use rtrim function to remove last comma and explode the removed string.
$imageExtract = rtrim("sample1,sample2,sample3,", ",");
$imageExtractExplode = explode(",", $imageExtract);
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}
OR substr($string, 0, -1);
$imageExtract = substr("sample1,sample2,sample3,", 0, -1);
$imageExtractExplode = explode(",", $imageExtract);
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}

You could use preg_split() instead of explode() as it gives you a way to ignore empty strings:
$imageExtractExplode = preg_split("/,/", $imageExtract, -1, PREG_SPLIT_NO_EMPTY);
That way you also avoid empty string problems if there are two commas in a row.
See details here: http://us1.php.net/manual/en/function.preg-split.php

$imageExtractExplode = explode(",", $imageExtract);
array_pop($imageExtractExplode); // THIS .. !
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}

$imageExtract = rtrim($imageExtract,',');
$imageExtractExplode = explode(",", $imageExtract);
foreach ($imageExtractExplode as $imageExtractFinal){
//my echo code
}

Are you using an earlier version of PHP? I don't seem to have that problem but I'm running 5.3.
// Explode the values
$imageExtractExplode = explode(",", $imageExtract);
// Run foreach loop
foreach ($imageExtractExplode as $imageExtractFinal) {
// Check to see if the value is empty or not. If it is empty, skip it.
if (!empty($imageExtractFinal)) {
//my echo code
}
}

You can use substr to extract part of the string.
$str = "sample1,sample2,sample3,";
$rs = substr($str, 0, -1); // returns "sample1,sample2,sample3"

I prefer using reset and end to generate a custom last() function - see this answer from Rok Kralj for details.
function last($array, $key) {
end($array);
return $key === key($array);
}
foreach($array as $key => $element) {
if (last($array, $key))
echo 'LAST ELEMENT!';
}

Related

i dont want to display comma after displaying last value

Display comma after displaying last value:
$len = count($boltpatterns);
foreach ($boltpatterns as $key => $boltpattern) {
$st1=$boltpattern['BP'];
$st2='-';
$pos=strpos($st1,$st2);
if($pos === false){
} else {
echo $st1;
if($key != $len - 1) {
echo ',';
}
}
}
You could have simply used array_column() and implode() function.
array_column() lists all your 'BP' keys into one single dimensional array.
implode() converts this single dimensional array $arr into string, separating each entry with a comma.
$arr = array_column($boltpatterns, 'BP');
echo implode(',', $arr);
Just add a new variable that will keep track of how many items you have looped through.
$len = count($boltpatterns);
$count = 1;
foreach ($boltpatterns as $key => $boltpattern) {
$st1=$boltpattern['BP'];
$st2='-';
$pos=strpos($st1,$st2);
if($pos === false){
} else {
echo $st1;
if($count != $len) {
echo ',';
}
}
++$count;
}
You can do this like this,
$valid_data = array();
foreach ($boltpatterns as $key => $boltpattern) {
if ( false !== strpos($boltpattern['BP'],'-') ){
$valid_data[] = $boltpattern['BP'];
}
}
echo implode(", ", $valid_data);
Explanation: Here we collect all the valid date we need to display to a new array. And we use PHP inbuilt function to display them.
Hope this will help you.
$arr = array_column($boltpatterns, 'BP');
echo rtrim(implode(', ', $arr), ', ');
This is an improved version of #object-manipulator's code, with rtrim removing the trailing comma.

Retrieve word from string

I have this code:
$getClass = $params->get('pageclass_sfx');
var_dump($getClass); die();
The code above returns this:
string(24) "sl-articulo sl-categoria"
How can I retrieve the specific word I want without mattering its position?
Ive seen people use arrays for this but that would depend on the position (I think) that you enter these strings and these positions may vary.
For example:
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
echo $arr[0];
$arr[0] would return: sl-articulo
$arr[1] would return: sl-categoria
Thanks.
You can use substr for that in combination with strpos:
http://nl1.php.net/substr
http://nl1.php.net/strpos
$word = 'sl-categoria';
$page_class_sfx = $params->get('page_class_sfx');
if (false !== ($pos = strpos($page_class_sfx, $word))) {
// stupid because you already have the word... But this is what you request if I understand correctly
echo 'found: ' . substr($page_class_sfx, $pos, strlen($word));
}
Not sure if you want to get a word from the string if you already know the word... You want to know if it's there? false !== strpos($page_class_sfx, $word) would be enough.
If you know exactly what strings you're looking for, then stripos() should be sufficient (or strpos() if you need case-sensitivity). For example:
$myvalue = $params->get('pageclass_sfx');
$pos = stripos($myvalue, "sl-articulo");
if ($pos === FALSE) {
// string "sl-articulo" was not found
} else {
// string "sl-articulo" was found at character position $pos
}
If you need to check if some word are in string you may use preg_match function.
if (preg_match('/some-word/', 'many some-words')) {
echo 'some-word';
}
But this solution can be used for a small list of needed words.
For other cases i suggest you to use some of this.
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
$result = array();
foreach($arr as $key=> $value) {
// This will calculates all data in string.
if (!isset($result[$value])) {
$result[$value] = array(); // or 0 if you don`t need to use positions
}
$result[$value][] = $key; // For all positions
// $result[$value] ++; // For count of this word in string
}
// You can just test some words like follow:
if (isset($result['sl-categoria'])) {
var_dump($result['sl-categoria']);
}

remove all but last comma

i have the following code:
while (list($key, $value) = each($arr)) {
$implode_keys_values = #"$key=$value,";
echo"$implode_keys_values";
}
which ends up echoing out xxxx=xxxx,xxxx=xxxx,xxxx=xxxx,xxxx=xxxx,
depending on how many keys/values there are.
how do I take this dynamically changing string and remove the very last comma on it?
keep in mind:
$implode_keys_values = substr($implode_keys_values,0,-1);
will not work, it will take out all the commas.
rtrim($implode_keys_values, ",") would cut trailing commas.
You can learn more about rtrim here at the PHP docs
$implode_keys_values = "";
while (list($key, $value) = each($arr)) {
$implode_keys_values .= #"$key=$value,";
}
echo rtrim($implode_keys_values, ",");
PHP has a function built in for that if the data in the array is not too complex (works for the xxxxxx values you have, can break with others):
echo http_build_query($arr, '', ',');
See http_build_query().
Another alternative is using iterators and checking if the current iteration is the last one. The CachingIterator::hasNext() method is helpful for that:
$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value) {
echo $key, '=', $value, $it->hasNext() ? ',' : '';
}
This variant does work with any data.
In your case, this would be a better way to implement implode():
$data = array();
while (list($key, $value) = each($arr)) {
$data[] = "$key=$value";
}
echo implode(",",$data);

I want to filter an array by first letter in PHP

<?php
function filter($fst, $arr){
$new_arr=array();
for($i=0;$i<=(count($arr)-1);$i++){
if(substr($arr[$i], 0, 1) == $fst){
$new_arr[] = $fst;
}
}
return $new_arr;
}
$list = Array("Apparel","Associations","Building/Grounds","Building/Materials",
"Dispensing","Disposables","Distributors");
$new_list[]=filter("A", $list);
for($i=0;$i<=(count($new_list)-1);$i++){
echo '<li>'.$new_list[$i].'</li>';
}
?>
I have created a function named filter() to filter the contents of an array that starts with a character like "a". It does not work at the moment.
First of all I assume that you want to print the word that was OK and not the character you was checking with? $new_arr[] = $fst; should be $new_arr[] = $arr[$i];
Secondly you're adding the resulting array of the function into a new array instead of assigning the array to your variable. $new_list[] = should be $new_list =.
Here's an updated version of your code. I've marked where I've made changes..
function filter($fst, $arr){
$new_arr=array();
for($i=0;$i<=(count($arr)-1);$i++){
if(substr($arr[$i], 0, 1) == $fst){
$new_arr[] = $arr[$i]; <----- Changed here
}
}
return $new_arr;
}
$list = Array("Apparel","Associations","Building/Grounds","Building/Materials",
"Dispensing","Disposables","Distributors");
$new_list=filter("A", $list); <----- And changed here
for($i=0;$i<=(count($new_list)-1);$i++){
echo '<li>'.$new_list[$i].'</li>';
}
Output:
<li>Apparel</li>
<li>Associations</li>
first
don't use
$new_list[] = filter("A", $list);
but simply
$new_list = filter("A", $list);
because your code will try to put an $new_array from filter() into next free index in array variable $new_list
second
$new_arr[] = $fst;
is wrong, because you're setting as new array value the A not matching word. use this instead:
$new_arr[] = $arr[$i];
for($i=0;$i<=(count($arr)-1);$i++){
if(substr($arr[$i], 0, 1) == $fst){
//$new_arr[] = $fst; // <-- Bug is here
$new_arr[] = $arr[$i]; // Try this
}
}
And another bug:
//$new_list[]=filter("A", $list); // This
$new_list = filter("A", $list); // Should be this
foreach($arr as $word) {
// do something with $word
}
reads better than a C-style for $i loop

PHP Last Array Key Issue

I have this simple code for pasting images from a directory, I've sorted them into an array but the problem I can't seem to work out is how to get the last array to be different.
This is my code so far:
foreach($images as $image){
echo("{image : '$image'}, ");
}
I'm looking to keep print the single items in the array but on the last one I'd like to not have the comma.
Any help would be great,
Thanks!
Simple.
function doit($image) {
return "{image: '$image'}"
}
$images = array_map('doit',$images);
$images = implode(', ',$images);
echo "{image : '".implode("'}, {image : '",$images)."'}";
Try:
<?php
$buffer = array();
foreach($images as $image){
$buffer[] = "{image : '$image'}";
}
echo implode(', ', $buffer);
Try using the key and the length of the array:
$arrLength = count($images);
foreach($images as $key=>$image){
echo("{image : '$image'}");
if($key < $arrLength - 1){ echo ", "; }
}
Or use an array_map:
function make_array($n)
{
return "{image: '$n'}"
}
$map = array_map("make_array", $images);
$new_array = implode(', ', $map);
You could do this attractively with a do..while loop:
$image = current($images);
do {
echo "{image : '$image'}";
} while (($image = next($images) && (print " ,"));
Note that you have to use print not echo there, as echo does not behave as a function.
The second part of the conditional only executes if the first part passes, so " ," will only be printed if another image exists.
If there is the possibility (as in, even the vaguest possibility) that your array may contain values that aren't non-empty strings, you'll need to be more verbose:
} while (
(false !== ($image = next($images)) &&
(print " ,")
);
I'm not convinced this is very readable, however, even split over multiple lines, so if this is the case I'd go for one of the other approaches.
Either use an if statement and check if it's the last and echo accordingly, or concatenate without echoing, trim the result after it's generated, and echo.
You could do if and else statements, where if its the last image print without comma else if it isn't print with comma.
$last = array_pop(array_keys($images));
foreach($images as $key => $image) {
if ($key == $last) {
... last image ,don't output comma
}
}

Categories