How to store in a variable the result of a function in PHP

How I could store the result of this function in a string:

for($i=0; $i<=($totRows-1); $i++)
    {
        if($i<($totRows-1))
        { echo $objects[$i]['id'].","; }
        else
        { echo $objects[$i]['id']; }
    }

And for example it returns:

6,8,9

and I want to save it as a variable such as $var then when typing the following code:

echo $var;

I would have the same string

6,8,9

Thanks!

Upvotes: 1

Views: 3064

Answers (3)

Galen
Galen

Reputation: 30170

function getIDs( array $objects ) {
    foreach( $objects as $obj ) {
        $obj_array[] = $obj['id']
    }
    return $obj_array;
}
echo implode( ',', getIDs( $objects ) );

or in PHP 5.3+

function getIDs( array $objects ) {
    return array_map( function($v){return $v['id'];}, $objects );
}
echo implode( ',', getIDs( $objects ) );

Upvotes: 1

genesis
genesis

Reputation: 50976

$text = "";
for($i=0; $i<=($totRows-1); $i++)
    {
        if($i<($totRows-1))
        { $text .= $objects[$i]['id'].","; }
        else
        { $text .= $objects[$i]['id']; }
    }

echo $text;

Upvotes: 4

Gazler
Gazler

Reputation: 84160

function foo($totRows, $objects)
{
    $return = "";
    for($i=0; $i<=($totRows-1); $i++)
    {
        if($i<($totRows-1))
        { $return .= $objects[$i]['id'].","; }
        else
        { $return.= $objects[$i]['id']; }
    }
    return $return;
}

$var = foo($totRows, $objects);
echo $var;

Upvotes: 4

Related Questions