Page 1 of 1
Arrays
Posted: Fri May 07, 2010 5:57 am
by toneburst
List newbie here, so hi guys.
I'm Alex, from sunny London. Been working with PHP for a while, on and off, but am completely self-taught when it comes to coding, so always value the advice of those with more experience/training/talent in the area than myself.
With that in mind, I'm currently doing this:
Code: Select all
$item = explode(" ", $string);
$item = $item[0];
to set $item to the first chunk of $string before the first space, and am wondering if there a more elegant way of doing the same thing, on a single line?
Cheers,
a|x
Re: Arrays
Posted: Fri May 07, 2010 8:33 am
by social_experiment
toneburst wrote:...to set $item to the first chunk of $string before the first space
With chuck do you mean the first item in the array? If so, you kindoff did it with
because equating a value to $array_name[0] gives that variable the value of whatever is inside $array_name[0]. You should just name your variable something different than the name of the array, $arrayItem or something.
Hope this helps.
Re: Arrays
Posted: Fri May 07, 2010 9:16 am
by toneburst
Hi social_experiment,
thanks for getting back to me so quickly.
I probably didn't explain myself very well. I'm basically trying to set $item to the first part of $string, before the first space in that string.
So, if my string is
"01 Dalston Junction"
I want $item to be "01".
The way I'm currently doing it works fine, but I'm always looking for more elegant ways of doing things, so I'd like to be able to do the same thing, but all in one line, without having to set $item to an array, and then a single string.
Any thoughts?
Thanks again,
a|x
Re: Arrays
Posted: Fri May 07, 2010 10:14 am
by social_experiment
np

. I think you are looking for this function
str_split(). It converts a string into an array. Here the example from the php manual.
Code: Select all
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
It splits the string into chunks and if you add the second argument, the chunks are that size. Hope this helps.
Re: Arrays
Posted: Fri May 07, 2010 11:08 am
by AbraCadaver
Elegant is subjective, but here are a few ways. With the exception of overwriting your array with the single item, your way gives you an array so that you have access to all of the words if needed. If you only want the first one, then these are one liners:
Code: Select all
// this just assigns the first item from the exploded array
list($item) = explode(" ", $string, 2);
// this does the same as above, just differently
$item = array_shift(explode(" ", $string, 2));
// this doesn't create an array, it just find the space and returns the chars preceding it
$item = substr($string, 0, strpos($string, ' '));
// if you know that you need the first two, then this will work
list($first, $second) = explode(" ", $string, 3);