-1

All viewers I need help regarding PHP explode() function.

$line = 'dd=541;nn=874;cc=21;mm=95;tt=41';
$lineexp = explode(';', $line);
print_r($lineexp);

This will produce the following output:

[
    0 => 'dd=541',
    1 => 'nn=874',
    2 => 'cc=21',
    3 => 'mm=95',
    4 => 'tt=41'
]

How can I get just the value of the array as array instead?

Desired output:

[
    0 => 541,
    1 => 874,
    2 => 21,
    3 => 95,
    4 => 41
]
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
  • Using a `foreach` loop… You could use explode again on the results, with "=" as parameter. Or you could use regex to clean each result. Or you could take a substr() of each result, as the "xx=" variables seem to be always the same lenght… – Takit Isy Mar 29 '18 at 14:21
  • You have fallen into the "I have a string, thus I shall use explode" trap. That's oftentimes the worst approach for string extraction. – mario Mar 29 '18 at 14:37
  • Well, filter your array entries by a simple callback function: `$result = array_map(function($item) { return filter_var($item, FILTER_SANITIZE_NUMBER_INT); }, $data);`. – Marcel Mar 29 '18 at 14:39

3 Answers3

3

Just one option to do it. Iterate over array and substr after = character:

$line = 'dd=541;nn=874;cc=21;mm=95;tt=41';
$lineexp = explode(';', $line);

$lineexp = array_map(function($item){
    return substr($item, strpos($item, '=')+1);
}, $lineexp);
Alexey Chuhrov
  • 1,787
  • 12
  • 25
1
<?php 
$line= "dd=541;nn=874;cc=21;mm=95;tt=41"; 
$lineexp = explode(';', $line);

$farray=array();
foreach ($lineexp as $n){
 $nv = explode("=",$n)[1];
array_push($farray,$nv);
 }
var_dump($farray);

?>

some thing like this i think http://sandbox.onlinephpfunctions.com/code/07a886132e8d0ae1c61f47997faa72d0cc33fd8f

Jehad Ahmad Jaghoub
  • 1,225
  • 14
  • 22
1

You could use array_map and use explode using the = as the delimiter and return the second part [1] which contains the number:

$line= "dd=541;nn=874;cc=21;mm=95;tt=41";
$lineexp = array_map("expl", explode(';', $line));

function expl($value) {
    return explode('=', $value)[1];
};

Or with inline anonymous function:

$lineexp = array_map(function ($a) {
    return explode('=', $a)[1];
}, explode(';', $line));

var_dump($lineexp);

That would give you:

array(5) {
  [0]=>
  string(3) "541"
  [1]=>
  string(3) "874"
  [2]=>
  string(2) "21"
  [3]=>
  string(2) "95"
  [4]=>
  string(2) "41"
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70