How to separate each result with a comma in PHP - php

So I'm using:
<?php print $variable; ?>
and sometimes there are multiple variables being printed, but I'm not able to tell how many. Is there a way of printing the variables separated by a comma, but only when there are more than one?
Thanks!

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
<?php
var_dump($variable);
?>

if your $variable is an array count it like count($variable) and than put you condition like
if(count($variable)>1) { $imp=implode(',',$variable); }
hope this will help you..

If it's not an array
<?php /* somwhere before... */ $sep = ''; ?>
<?php print $sep.$variable; $sep = ',' ?>
If it's array
<?php print implode( ',', $variable ); ?>

Related

How can I avoid printing the separator when elements are empty in the join()?

Here is my code:-
echo join(',', ['','']);
As you know, it prints just a comma. I want to avoid that. Because elements are empty and the only comma doesn't make any sense. Also the comma should be deleted in this:
echo join(',', ['sth','']);
// the expected result: sth
How can I do that?
Just remove empty items of the array. You can do that simply by using array_filter() function. So try this:
echo join(',', array_filter(['sth','']));
Online Demo

Getting the value outside the foreach php loop

Here is the code used to get the ids of a images in a gallery
<?php $images = get_field('photogallery');?>
<?php foreach( $images as $image ): ?>
<?php echo $image['ID']; ?>
<?php echo ','; ?>
<?php endforeach; ?>
I get the output
1102 , 3380 , 3348 , 3354 , 3355 ,
I would like to get this outside the loop because the result must be used in other shortcode also I see there is a whitespace after every number.
the result must be
1102,3380,3348,3354,3355
Please help me.. thanks
You don't need to put <?php ... ?> everytime everywhere for each statement. Keep in mind that each time you close with ?> all characters are sent to the client until the next opening <?php, that's why you obtain spaces around each comma:
<?php foreach( $images as $image ): ?>#
#####<?php echo $image['ID']; ?>#
#####<?php echo ','; ?>#
<?php endforeach; ?>
(I changed white-spaces to #, this way you can see characters sent to the client (the browser)).
You can use array_map to "filter" only ID items and implode to join them , then you only need to store the result in a variable ($result here).
<?php
$images = get_field('photogallery');
$result = implode(',', array_map(function ($i) { return $i['ID']; }, $images));
echo $result;
?>
Now you can use $result later everywhere you want.
Much simpler:
<?php echo implode(',' array_column($images, 'ID')); ?>
extract the ID values using array_column()
implode() those array values using a comma

Iterating over PHP array to create Javascript array with PHP foreach

I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:
<?php
$array = array(StdObject,StdObject,StdObject);
?>
//later that page...in JavaScript
var list = [
<?php foreach($array as $value):?>
'<?=$value->some_letter_field?>',
<?endforeach;?>
];
Unfortunatly, what this code does is produce output that looks like this:
var list = ['a','b','c',];
Notice that extra comma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra comma doesn't get printed, producing a properly formatted JavaScript array?
The expected output should be:
var list = ['a','b','c'];
I appreciate your help in advance.
You don't need to do this yourself, PHP has a function called json_encode that does what you want. If for some reason you don't have PHP 5.2.0, there are a lot of implementations in the comments of that page to get around that.
Use implode() to glue up array elements. It will take care about commas
//later that page..in JavaScript
var list = ['<?=implode("', '", $array)?>'];
You can use this to generate the json array:
$list = json_encode($array);
And then read it in Javascript:
var list = <?=$list?>
This will do the trick:
<?php
$filtered = array();
foreach($array as $value) {
$filtered[] = $value->some_letter_field;
}
echo 'var list = ' . json_encode($filtered);
?>
How about converting array to a valid JSON object?
var list = JSON.parse("<?php echo json_encode($array); ?>");
Anyway, do you really need to generate JS code on the fly? Isn't there another way to complete your task? JS generation is often considered a hack, and it can be avoided easily in many cases.
If you insist in keeping your current code for whatever reason, just:
var list = [
<?php foreach($array as $value): ?>
$output[] = "'".$value->some_letter_field."'";
<?php endforeach; ?>
echo implode(',', $output);
];

Php Implode Not Working with my code

i have an array and i want to convert this array in comma seprated string by implode function but this is not working. my code is below.
<?php foreach ($article['hashtags'] as $hashtags) { ?>
<?php $hastagg=mysql_real_escape_string(implode(',',$hashtags)) ?>
<a><?php echo $hastagg; ?></a>
<?php } ?>
Have you tried this:
<?php
$hastagg = htmlentities(implode(',' ,$article['hashtags'])) ;
echo '<a>'.$hastagg.'</a>';
?>
I don't know about structure of $article array. But I have a feeling that foreach is unnecessary:
$hashtagg = implode(',', $article['hashtags']);
And why are you using mysql_real_escape_string for output? You can use htmlspecialchars or some other functions.

php arrays creating dynamically giving incorrect values

I want to create a array with values:
3,2,1.... and I want to use array_push and a forloop.
I have written the following code is not working..
============
<?PHP
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$temp4=1;
$temp5=1;
$arraytemp=array();
for($i=0;$i<4;$i++)
{
$r="temp";
$dd=$r.$i;
array_push($arraytemp,$dd);
}
echo $arraytemp[3];
?>
can you please let me know what I am missing
This is how should you assign $dd
for($i=0;$i<4;$i++)
{
$dd=${"temp".$i};
array_push($arraytemp,$dd);
}
your $dd has the name of your var as a string. you want to use this for this technique:
array_push($arraytemp,$$dd);
Pay attention to the double $$ :)
What happens here is the following: the $dd gets replaced by the string it contains. so your call
array_push($arraytemp,$dd);
will do this:
array_push($arraytemp,'temp0');
But you want this:
array_push($arraytemp,$temp0);
so you need to show you want an acutal $var with that name, so you add the $. It's just the way the syntax works, neccessairy to distinguish between a normal string and a string that's supposed to be a variable
confusing what do you want to achieve here, do you want to:
create array with value: temp0, temp1, temp2 ...
for($i=0;$i<4;$i++){
array_push($array,"temp{$i}");
}
echo $array[3];
create array with value: 0, 1, 2, 3 ..
for($i=0;$i<4;$i++){
array_push($array,$i);
}
echo $array[3];
create array with value based on your defined variable above ($temp0, $temp1 ...)
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$array = array();
for($i=0;$i<4;$i++){
$val = "temp{$i}";
array_push($array,$$val);
}
echo $array[3];
Easiest way, going by what you're requesting, although you didn't specify how many numbers you wanted to add. so for loop won't work that way. you're best off with a while loop.
$foo = array();
$i = 1;
while (some end condition) {
array_push($foo, $i);
$i++;
}
print_r($foo);

Categories