0

I have this

<?php 

foreach ($results as $row):

    if ($row['title'] == "") $row['title'] = date('d-m-Y', strtotime($row['date']));
    if (strlen($row['text']) > 100) $row['text'] = substr($row['text'], 0, 100) . "...";

?>
        <div>
            <a href="<?php echo $row['url'] ?>">
            <img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
            <h1><?php echo $row['title'] ?></h1>
            <p><?php echo $row['text']; ?></p>
            </a>
        </div>
<?php endforeach ?>

Right after the foreach starts I do some "house cleaning" where I substitute the date if there is no title and reduce the text to 100 characters etc.

Repeating this over and over is not very efficient, so it would be better to create a function right?

My question is how do I do this?

Thanks for your help

4
  • 2
    Even if you put it in a function the code will still execute the same number of times. Putting it in a function is only helpful if you use the same code somewhere else. Commented Mar 1, 2012 at 20:01
  • What does that mean Dagon? Can you please elaborate. Commented Mar 1, 2012 at 20:01
  • Yotaware that's what I wan't to do. I want to use this function in other places. Commented Mar 1, 2012 at 20:03
  • I'm using Codeigniter. Which allows me to define a function and load it globally so all my scripts have access to it. Commented Mar 1, 2012 at 20:05

1 Answer 1

4

Try rewriting your code like this. Just add more of your required functionality to the processRowData() function.

<?php

function processRowData($row) {
    if ($row['title'] == "") {
        $row['title'] = date('d-m-Y', strtotime($row['date']));
    }
    // Do more with other elements from $row ...
    // when done, return the modified $row array
    return $row;
}

?>

<?php

foreach ($results as $row) {
    // Alter the row data with your function
    $row = processRowData($row);
?>

<div>
    <a href="<?php echo $row['url'] ?>">
    <img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
    <h1><?php echo $row['title'] ?></h1>
    <p><?php echo $row['text']; ?></p>
    </a>
</div>


<?php } ?>
Sign up to request clarification or add additional context in comments.

1 Comment

You can pass variable by reference processRowData(&$row) and then you don't have to return it as it would be changed on the fly. Additionally, in mixed html/php its better to use foreach(): and endforeach;, not brackets { ... }, because it's more readable.

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.