Shortcut for: $foo = explode(“ ”, “bla ble bli”); echo $foo[0]

后端 未结 9 1377
清歌不尽
清歌不尽 2020-12-19 15:48

is there a way to get the n-th element of a splitted string without using a variable?

My PHP code always looks like this:

$foo = explode(\" \", \"bla         


        
相关标签:
9条回答
  • 2020-12-19 16:05

    The following is probably the cleanest way I can think of doing what OP has requested. It defines a function, but no variables of it's own and it'll get the job done for just about any situation:

    function at(&$arr, &$pos) { return $arr[$pos]; }

    Example usage:

    echo at( explode('|', 'a|b|c|d'), 1 ); // Outputs 'b'

    The function is a single line of code and wouldn't be hard to commit to memory. If you're only using it once, you can define it in the local scope of where it'll be used to minimize code clutter.
    As a slight added benefit, because the function does no checks on $arr or $pos, it'll throw all the same errors that it would if you tried to access a non-existent index for an array, or will even return the individual characters in a string or items in a key-value paired array.

    0 讨论(0)
  • 2020-12-19 16:07

    try this:

    its one line:

    <?php
    
    echo (($f=explode(" ", "bla ble bli"))?$f[0]:'');
    
    ?>
    

    result here: http://codepad.org/tnhbpYdd

    0 讨论(0)
  • 2020-12-19 16:11

    close. the right track is making a function or method for something that gets repeated.

    function extract_word($input, $index) {
        $input = explode(' ', $input);
        return $input[$index];
    }
    

    add a third argument of $separater = ' ' if you may have different word separaters.

    0 讨论(0)
  • 2020-12-19 16:14

    Not as far as I know although you could define a function and use that.

    function firstWord($string) {
      $foo = explode(" ", $string);
      return $string;
    }
    
    0 讨论(0)
  • 2020-12-19 16:16

    Why not just do:

    function splode($string, $delimiter, $index){
     $r = explode($delimiter, $string);
     return $r[$index];
    }
    

    I use like a hojillion little functions like this.

    0 讨论(0)
  • 2020-12-19 16:21

    I don't know of a way to do what you want, even though I've wanted to do the same thing many times before. For that specific case you could do

    $bar = substr($foo, 0, strpos($foo, " "));
    

    which stops there being one extra variable, but isn't exactly what you wanted.

    0 讨论(0)
提交回复
热议问题