Page 1 of 1

using expressions in echo?

Posted: Tue Apr 01, 2008 12:24 pm
by haosmark
is it possible?
for example:

Code: Select all

 
    function find_value($array, $value) {
        for($i = 0; $i < sizeof($array); $i++) {
            if($array[$i] == $value) {
                return "{$array[$i]} is $i";
            }
        }
    }
    
    $fruits = array("orange", "apple", "banana");
    
    echo find_value($fruits, "apple");
 
i want to increase $i by 1 after array element was displayed.
stuff like

Code: Select all

return "{$array[$i]} is $i++";
or

Code: Select all

return "{$array[$i]} is {$i++}";
isn't working. Is it possible to achieve this without creating another var? :banghead:

Re: using expressions in echo?

Posted: Tue Apr 01, 2008 12:36 pm
by onion2k
Your code works fine. Seems a bit silly incrementing $i after you've returned from the function and $i has been destroyed, but the code works exactly how I would expect it to nonetheless. If you want to return "apple is 2" you just need to increment the value of i before it's returned ... eg

Code: Select all

return "{$array[$i]} is ".++$i;

Re: using expressions in echo?

Posted: Tue Apr 01, 2008 2:21 pm
by John Cartwright

Code: Select all

 
function search($stack, $needle) 
{
   $search = array_search($needle, $stack);
   return $value .' is at '. ++$search;
}
 
:?:

I don't really understand the business on what your expecting to be returned, so I may be wrong.

Re: using expressions in echo?

Posted: Tue Apr 01, 2008 2:40 pm
by haosmark
That's exactly what i was trying to do, thanks :D !