0

Problem: Hi, Im having a hard time making a foreach in PHP, that has arrays of strings, then I will add all those strings in a one single string or store in a single variable.

Purpose: My purpose for this is because I want to make an echo substr() of the total of all strings which is for my other reasons.

What I've done so far:

<?php 

    $values = array();

    foreach ($acknowledgementspecifics as $specifics);
    {
    ?>  

    <?php $values = array[]("".$specifics->feetype_name." (".$specifics->month_date.") ".$specifics->payment_amount.", "); ?>

    <?php
     }

// (Combine all Arrays)

// $totalvalue = (total of all combined strings);
?>

3 Answers 3

2

Two issues:

  • The ; at the end of the foreach line will create a loop without any body. The part that follows it is not part of the foreach body. So remove the ;.

  • The syntax to append to an array is not $values = array[]( ... ), but $values[] = ...

After those fixes, you will have the array of strings, which you then need to concatenate to one string, which you can do with implode. You need to provide a delimiter to separate the strings (e.g. \n or <br>):

$values = array();
foreach ($acknowledgementspecifics as $specifics) {
    $values[] = $specifics->feetype_name . " (".
                $specifics->month_date . ") ".
                $specifics->payment_amount . ", "; 
}
// (Combine all Arrays)
$totalvalue = implode("\n", $values);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is the best answer, easy to understand and thanks for those corrections.
0

if you want to store all values in a string in a forecah loop, ignore use of array, use (.=) operator. now you can use use substr() function. see the code - use substr() function

<?php 
    $values = "";
    foreach ($acknowledgementspecifics as $specifics){
        $values. = "".$specifics->feetype_name." (".$specifics->month_date.") ".$specifics->payment_amount.", ";
    }

    $totalvalue=$values; // (All Values)
//now you can use substr()
?>

Comments

0

To add the string to the array...

$values[] = $specifics->feetype_name
       ." (".$specifics->month_date.") "
       .$specifics->payment_amount;

And to add them together use either implode(',', $values) or just implode($values)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.