Explode to int php

Explode comma separated integers to intvals? [duplicate]

You can always write a small helper function to grab elements from functions that return arrays: EDIT: PHP 5.4 will support array dereferencing, so you will be able to do: Solution 2: You are correct with your second code-block. , and other functions can’t return a fully formed array for immediate use,and so you have to set a temporary variable. Solution 2: Use something like this: http://php.net/manual/en/function.array-walk.php Solution 3: For the most part you shouldn’t really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can with or : If you need something a bit more verbose, you can also look into : That could be particularly useful if you’re trying to cast dynamically: Solution 4: Since $thestring is an string then you will get an array of strings.

Explode comma separated integers to intvals? [duplicate]

Say I have a string like so $thestring = «1,2,3,8,2» .

If I explode(‘,’, $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?

array_map also could be used:

$s = "1,2,3,8,2"; $ints = array_map('intval', explode(',', $s )); var_dump( $ints ); 
array(5) < [0]=>int(1) [1]=> int(2) [2]=> int(3) [3]=> int(8) [4]=> int(2) > 
$data = explode( ',', $thestring ); array_walk( $data, 'intval' ); 

For the most part you shouldn’t really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval :

$arr = explode(',','1,2,3'); // use floatval if you think you are going to have decimals array_walk($arr,'intval'); print_r($arr); Array ( [0] => 1 [1] => 2 [2] => 3 ) 

If you need something a bit more verbose, you can also look into settype :

$arr = explode(",","1,2,3"); function fn(&$a) array_walk($f,"fn"); print_r($f); Array ( [0] => 1 [1] => 2 [2] => 3 ) 

That could be particularly useful if you’re trying to cast dynamically:

class Converter < public $type = 'int'; public function cast(&$val)< settype($val, $this->type); > > $c = new Converter(); $arr = explode(",","1,2,3,0"); array_walk($arr,array($c, 'cast')); print_r($arr); Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 0 ) // now using a bool $c->type = 'bool'; $arr = explode(",","1,2,3,0"); array_walk($arr,array($c, 'cast')); var_dump($arr); // using var_dump because the output is clearer. array(4) < [0]=>bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) > 

Since $thestring is an string then you will get an array of strings.

Читайте также:  Team noblock css v34

Just add (int) in front of the exploded values.

$arr = explode(',', $thestring); array_walk($arr, 'intval'); 

Php — How can I explode and trim whitespace?, By combining some of the principals in the existing answers I came up with. preg_split (‘/\s*,+\s*/’, ‘red, green thing ,, ,, blue ,orange’, NULL, PREG_SPLIT_NO_EMPTY);

PHP explode array then loop through values and output to variable

The string I am trying to split is $item[‘category_names’] which for example contains Hair, Fashion, News

I currently have the following code:

$cats = explode(", ", $item['category_names']); foreach($cats as $cat) < $categories = "\n"; > 

I want the outcome of $categories to be like the following so I can echo it out later somewhere.

Not sure if I am going the right way about this?

In your code you are overwritting the $categories variable in each iteration. The correct code would look like:

$categories = ''; $cats = explode(",", $item['category_names']); foreach($cats as $cat) < $cat = trim($cat); $categories .= "\n"; > 

update: as @Nanne suggested, explode only on ‘,’

$item['category_names'] = "Hair, Fashion, News"; $categories = "\n\n"; echo $categories; 
$cats = explode(", ", $item['category_names']); foreach($cats as $cat) < $categories = "\n"; > 

the $categories string is overwritten each time, so «hair» and «fasion» are lost..

if you however add a dot before the equal sign in the for loop, like so:

$cats = explode(", ", $item['category_names']); foreach($cats as $cat) < $categories .= "\n"; > 

the $catergories string will consist of all three values 🙂

PHP explode array by loop demo: http://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2

PHP explode and assign it to a multi-dimensional array, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

PHP — Using explode() function to assign values to an associative array

I’d like to explode a string, but have the resulting array have specific strings as keys rather than integers:

ie. if I had a string «Joe Bloggs», Id’ like to explode it so that I had an associative array like:

$arr['first_name'] = "Joe"; $arr['last_name'] = "Bloggs"; 
$str = "Joe Bloggs"; $arr['first_name'] = explode(" ", $str)[0]; $arr['last_name'] = explode(" ", $str)[1]; 

which is inefficient, because I have to call explode twice.

$str = "Joe Bloggs"; $arr = explode(" ", $str); $arr['first_name'] = $arr[0]; $arr['last_name'] = $arr[1]; 

but I wonder if there is any more direct method.

I would use array_combine like so:

$fields = array ( 'first_name', 'last_name' ); $arr = array_combine ( $fields, explode ( " ", $str ) ); 

EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.

You can make use of list PHP Manual ( Demo ):

$str = "Joe Bloggs"; list($arr['first_name'], $arr['last_name']) = explode(" ", $str); 
Array ( [last_name] => Bloggs [first_name] => Joe ) 

You cannot do explode(» «, $str)[0] in PHP

list($arr['first_name'], $arr['last_name']) = explode(" ", $str); 

Php — Extract a single (unsigned) integer from a string, If it is possible/unknown for the integer value to occur at the start of the string, then prepend a non-numeric character to the input string before scanning it. The following technique matches leading non-digits (and ignores them with * after the % ), then matches the first occurring sequence of digits and casts the …

PHP explode and array index

How can I get the following code to work?

I only see solutions looking like this:

As others have said, PHP is unlike JavaScript in that it can’t access array elements from function returns. The second method you listed works. You can also grab the first element of the array with the current() , reset() , or array_pop() functions like so:

$a = current( explode( 's', $str ) ); //or $a = reset( explode( 's', $str ) ); //or $a = array_pop ( explode( 's', $str ) ); 

If you would like to remove the slight overhead that explode may cause due to multiple separations, you can set its limit to 2 by passing two after the other arguments. You may also consider using str_pos and strstr instead:

$a = substr( $str, 0, strpos( $str, 's' ) ); 

Any of these choices will work.

EDIT Another way would be to use list() (see PHP doc). With it you can grab any element:

list( $first ) = explode( 's', $str ); //First list( ,$second ) = explode( 's', $str ); //Second list( ,,$third ) = explode( 's', $str ); //Third //etc. 

That not your style? You can always write a small helper function to grab elements from functions that return arrays:

function array_grab( $arr, $key ) < return( $arr[$key] ); >$part = array_grab( explode( 's', $str ), 0 ); //Usage: 1st element, etc. 

EDIT: PHP 5.4 will support array dereferencing, so you will be able to do:

$first_element = explode(',','A,B,C')[0]; 

You are correct with your second code-block. explode , and other functions can’t return a fully formed array for immediate use,and so you have to set a temporary variable. There may be code in the development tree to do that, but the only way to get the elements you need for now, is the temporary variable.

$a = array_shift(array_slice(explode("s", $str), 0, 1))); 

This is the best way I have found to get a specific element from an array from explode.

  • Explode returns an array on delimiter
  • array_slice($arrayname, $offset, $length) gives you a new array with all items from offset, lenght
  • array_shift($array) gives you the first (and in this case, the only) item in the array passed to it.

This doesen’t look pretty, but does the same as:

There must be a better way to do this, but I have not found it.

Update: I was investigating this because I wanted to extract a portion of a URL, so i did the following tests:

function urlsplitTest() < $url = 'control_panel/deliveryaddress/188/edit/'; $passes = 1000000; Timer::reset(); Timer::start(); $x =0; while ($x<$passes) < $res = array_shift(array_slice(explode("/", $url), 2, 1)); $x++; >Timer::stop(); $time = Timer::get(); echo $res.'
Time used on: array_shift(array_slice(explode("/", $url), 2, 1)):'.$time; Timer::reset(); Timer::start(); $x =0; while ($x <$passes) < $res = array_get(explode("/", $url), 2); $x++; >Timer::stop(); $time = Timer::get(); echo $res.'
Time used on: array_get(explode("/", $url), 2): '.$time; Timer::reset(); Timer::start(); $x =0; while ($x <$passes) < $res = substr($url, 30, -6); $x++; >Timer::stop(); $time = Timer::get(); echo $res.'
Time used on: substr($url, 30, -6): '.$time; > function array_get($array, $pos)

The results were as following:

Time used on: array_shift(array_slice(explode("/", $url), 2, 1)):7.897379 Time used on: array_get(explode("/", $url), 2): 2.979483 Time used on: substr($url, 30, -6): 0.932806 

In my case i wanted to get the number 188 from the url, and all the rest of the url was static, so i ended up using the substr method, but for a dynamic version where lenth may change, the array_get method above is the fastets and cleanest.

PHP explode and array index, explode, and other functions can’t return a fully formed array for immediate use,and so you have to set a temporary variable. There may be code in the development tree to do that, but the only way to get the elements you need for now, is the temporary variable.

Источник

Оцените статью