Lewis
Lewis

Reputation: 14866

PHP - Return an array from loop's value in a function

For example, I have a function like this:

function loopValues()
{
    $a = array('a','b','c');
    foreach($a as $b)
    {
        $c = $b.'e';
        echo $c;
    }
}

How could I return its value aebece in an array like ('ae','be','ce')?

Upvotes: 2

Views: 2159

Answers (4)

user3393016
user3393016

Reputation: 1

function loopValues(){
   $a = array('a','b','c');
   for($i=0;$i<count($a);$i++){
      $a[$i] .= 'e';
   }
   return $a;
}

Upvotes: 0

John Conde
John Conde

Reputation: 219804

$a = array('a','b','c');
$b = array_map(function($ele) {
    return $ele .= 'e';
}, $a);

See it in action

Upvotes: 3

Nouphal.M
Nouphal.M

Reputation: 6344

Try

function loopValues()
{
    $a = array('a','b','c');
    $result = array();
    foreach($a as $b){
        $result[] = $b.'e';
    }
    return $result;
}

$r = loopValues();
print_r($r);

See demo here

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94662

Simple, try this:

function loopValues()
{
    $a = array('a','b','c');
    $r = array();
    foreach($a as $b)
    {
        $c = $b.'e';
        $r[] = $c;
    }
    return $r;
}

Upvotes: 1

Related Questions