Re: array question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, Dec 17, 2010 at 15:52, Sorin Buturugeanu <mail@xxxxxxx> wrote:
> Hello all!
>
> I have a question regarding arrays and the way I can use a value.
>
> Let's say I have this string:
>
> $s = 'banana,apple,mellon,grape,nut,orange'
>
> I want to explode it, and get the third value. For this I would normally do:
>
> $a = explode(',', $s);
> echo $s[2];
>
> That's all fine, but is there a way to get the value directly, without
> having to write another line in my script. I mean something like this:
>
> echo explode(',', $s)[2];
>
> or
>
> echo {explode(',', $s)}[2];
>
> I couldn't find out this answer anywhere, that's why I posted here.

    Unfortunately, no --- at least, not yet.  Chaining discussions
come up now and again, so it's quite possible that future versions of
PHP will have something similar.  That said, for now you could do
something like this:

<?php
/**
 * mixed return_item( string $car, mixed $pos )
 *  - $str     The original string
 *  - $char    The delimiting character(s) by which to explode
 *  - $pos     The position to return
 *  - $shift   Whether or not we should see 1 as the first array position
 */
function return_item($str,$char,$pos=null,$shift=false) {

    // Make sure $char exists in $str, return false if not.
    if (!strpos($str,$char)) return false;

    // Split $char by $str into the array $arr
    $arr = explode($char,$str);

    // If $pos undefined or null, return the whole array
    if (is_null($pos)) return $arr;

    // If $pos is an array, return the requested positions
    if (isset($pos) && is_array($pos) && !empty($pos)) {

        // Instantiate a second array container for return
        $ret = array();

        // Iterate
        foreach ($pos as $i) {

            // This is just in case it was given screwy or a number as
a non-integer....
            if (!is_int($i) && is_numeric($i)) $i = (int)round($i);

            // Make sure $i is now an integer and that position exists
            if (!is_int($i) || !isset($arr[$i]) || empty($arr[$i])) continue;

            // If all seems okay, append this to $ret
            $ret[] = $arr[$i];
        }

        // Return the array
        return $ret;
    }

    /**
      * If $pos is a number (integer or round()'able number),
      * we'll go ahead and make sure the position is there.
      * If so, we'll return it.
      */
    if (is_int($pos) || is_numeric($pos)) {

        // This is just in case it was given screwy or as a non-integer
        if (!is_int($pos)) $pos = (int)round($pos);

	// If we want to start the array count at 1, do that now....
        if (isset($shift) && ($shift === true || $shift === 1)) {

		// .... but only if the number isn't zero
		if ($pos !== 0) --$pos;

	}

        // Return the single position if it exists
        if (isset($arr[$pos]) && !empty($arr[$pos])) return $arr[$pos];
    }

    /**
     * If we've failed every case, something is either
     * wrong or we supplied bad data.  Return false.
     * Either way, feel free to add some trigger_error()
     * stuff here if you want to have the function hold
     * your hand.
     */
    return false;
}



/**
 * Some simple examples
 */

$foo = 'apple,banana,carrot,orange,carrot,lettuce,tomato,beer,carrot,idiot';

return_item($foo,',',7); // Returns 'beer'
return_item($foo,'carrot',0); // Returns 'apple,banana,'
return_item($foo,','); // Returns all items in an array
return_item($foo,',',array(0,'2',6.6)); // Returns array: apple,carrot,beer
return_item($foo,',',1,true); // Returns 'apple'
?>


    Of course, as with almost all code I submit here, it's typed
directly into this window and is untested, so you use it at your own
risk, your mileage may vary, see a doctor if you have an erection
lasting more than four hours, et cetera.

    Happy Friday, all.

-- 
</Daniel P. Brown>
Network Infrastructure Manager
Documentation, Webmaster Teams
http://www.php.net/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux