using expressions in echo?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
haosmark
Forum Newbie
Posts: 10
Joined: Wed Mar 19, 2008 12:10 pm

using expressions in echo?

Post 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:
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: using expressions in echo?

Post 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;
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: using expressions in echo?

Post 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.
haosmark
Forum Newbie
Posts: 10
Joined: Wed Mar 19, 2008 12:10 pm

Re: using expressions in echo?

Post by haosmark »

That's exactly what i was trying to do, thanks :D !
Post Reply