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
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.
try this:
its one line:
<?php
echo (($f=explode(" ", "bla ble bli"))?$f[0]:'');
?>
result here: http://codepad.org/tnhbpYdd
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.
Not as far as I know although you could define a function and use that.
function firstWord($string) {
$foo = explode(" ", $string);
return $string;
}
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.
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.