Foreach loop with Concatenation assignment - php

<?php
$names =array('Alex','Billy','Tabby');
$names_str=null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key!= (count($names)-1))
{
$names_str.=', ';
}
}
echo $names_str;
?>
why do we set names_str=null?
why do we put count($names-1)) how does this loop work?

<?php
$names = array('Alex','Billy','Tabby');
$names_str = null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key != (count($names) - 1))
{
$names_str .=', ';
}
}
echo $names_str;
?>
Why do we set $names_str = null?
It is being initialized outside of the loop. If this is a string to be returned, technically doing $names_str = ""; would work better if you want a default value to show and aren't doing some sort of empty/null check...
Why do we put count($names-1))?
This checks the key # e.g. (0,1,2) against the count/length of the array minus 1 (array starts at 0), to see if we are referencing the last key/value pair in the array, to determine if the string should show a comma between the current value and next value, or not. If it's the last value, we don't want to show a "," at the end of the string.
How does this loop work?
$names_str .= $name; concatenates the $name values to the initial string, with the if/key check placing commas between each value. See above about the count. So you end up with "Alex, Billy, Tabby" as the final value for $names_str.
A better way to do this is to use PHP's implode function:
$comma_separated = implode(",", $names);
This would give you the same comma separated list.

Related

store value in a variable seperated by comma (,)

I have a foreach loop. which has a variable. how to store variable values in a single variable separated by comma,
foreach($variable as $key => $value){
$variable = $value->Id;
}
Do not use the same name of variable already used.
$otherV = '';
foreach($variable as $key => $value){
if ($otherV) $otherV .= ',';
$otherV .= $value->Id;
}
Use php implode() function:
$str = implode(',',$array);
See on php.net http://php.net/manual/en/function.implode.php
If your $variable is Object, first convert it to array with get_object_vars()

How to add text to array in cycle

I get some information from database! I need to place it on the array! How to add value to array in cycle???
I did this, but it did not wirk:
a[]='';
while ($p = mysqli_fetch_assoc($queryAns)) {
$countAnswers++;
a[] = $p['name'];
$arr .= $countAnswers.") "." ".$p['name']."\n";
}
The .= operator in PHP is used to concatenate strings. In order to append a new element to your array you need to do:
array_push($arr, $countAnswers.") "." ".$p['name']."\n");

Retrieving values crossing arrays gives unlogic result

In Drupal context, while printing checked exposed filters in a somehow standard code snippet, I can't print more than one value, and I can't find the missing logic of my foreach loop :
<?php
foreach ($exposed_filters as $filter => $value) {
if ($filter == 'foo') {
$field = field_info_field('field_foo');
$allowed_values = list_allowed_values($field);
//returns an array with 14 string values & numeric keys
//e.g array(0=>'bla', 1=>'bar', 2=>'xx', 3=>'yy')
$h = explode(',', $value);//returns checked ids of foo filter e.g array(0 => 2, 1=>3)
$exp_heb = '';
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[$v] . ', ';
}
$exp_heb = substr($exp_heb, 0, -2);
print $exp_heb;
}
}
?>
Should return : xx, yy but I get xx,,
I checked step by step printing out my arrays, values... everything's looks fine but result is wrong. Do I need a rest ???
This is dpm($allowed_values) output
May be this line cuts your output?
$exp_heb = substr($exp_heb, 0, -2);
I got it working. I have to get the integer value of my variable, before passing it as a key :
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[intval($v)] . ', ';
}
For a reason I would be glad to be taught, even if it's always an id, and prints out a number, first time it's passed as integer, but then not.

The word Array is displayed as the first item

I am getting the values from an array this is taken from jQuery.serialize() just an input field. I then send then form data to a sendMail page.
Display the results in an email and the word Array is the first word then the value inputted follows, the rest of the data displayed is ok.
I have four arrays and in front of each the word Array appears.
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty .= $value . "<br>";
}
$desc = $_POST['description'];
foreach($desc as $value)
{
$desc .= $value . "<br>";
}
$options = $_POST['options'];
foreach($options as $value)
{
$options .= $value . "<br>";
}
$price = $_POST['price'];
foreach($price as $value)
{
$price .= $value . "<br>";
}
input would be qty: 1, Desc: description, options: small, price: 1.99
output is Array 1, Array description, Array options, Array small.
only on the first line the rest of the lines are ok.
You are concatenating to the POST array you should do this instead:
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty2 .= $value . "<br>";
}
echo $qty2;
Each part of your code contain the inconsistency of both assuming you have an array as POST-data and then assigning it as an string.
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$possible_array .= $value . "<br>"; // < - here you use $possible_array as a string
}
One way forward should be to assign the string value to another string:
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$string .= $value . "<br>"; // < - change to a new string
}
However it seem not probable that you actually have POST-data in arrays here I guess you send different items which each have the properties qty, description etc
I think you would like to use a solution where you iterate (foreach) on product info as an two-dimensional array, like $_POST['products']['qty'] where products is an array. But to help you further you would need to include your POST-data to see how its structured/serialized.
That happens because you append the value of each array to the array itself. Due to the value being a string the result also becomes a string. So the array will implicitly be casted to a string which results in the word "Array".
Possible solution:
$qtyList = implode('<br>' , $_POST['qty']);

PHP - Search array for string

I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16

Categories