1

I have an array that looks something like this:

Array ( 
[0] => Array ( [country_percentage] => 5 %North America ) 
[1] => Array ( [country_percentage] => 0 %Latin America )
)

I want only numeric values from above array. I want my final array like this

Array ( 
[0] => Array ( [country_percentage] => 5) 
[1] => Array ( [country_percentage] => 0)
)

How I achieve this using PHP?? Thanks in advance...

1
  • 3
    There are some ways you can achieve this. But have you tried anything? Commented May 11, 2016 at 10:06

8 Answers 8

3

When the number is in first position you can int cast it like so:

$newArray = [];

foreach($array => $value) {

   $newArray[] = (int)$value;

}
Sign up to request clarification or add additional context in comments.

Comments

1

I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:

for($i=0; $i < count($arrays); $i++){
    $arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}

Ideone Demo


Update Based on your comment:

for($i=0; $i < count($arrays); $i++){
    if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
       echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
  }
}

4 Comments

1 more Question please. Now, how can I extract string value from array and based on that string I show the numeric value. For Example:- if(string==North America){ echo 5 }.. Thanks in advance..
Please check the updated answer. If my answer helped you, please mark it as the correct answer, thank you !
Parse error: syntax error, unexpected '{'.. when I removed this code then everything is fine.. what's the error then??
There was a parenthesis missing, fixed now.
1

Try this:

$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
  $int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
  $result[] = array('country_percentage' => $int);
}

Comments

1

Try this one:-

$arr =[['country_percentage' => '5 %North America'],
       ['country_percentage' => '0 %Latin America']];

$res = [];
foreach ($arr as $key => $val) {
    $res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);

output:-

Array
(
    [0] => Array
        (
            [country_percentage] => 5
        )

    [1] => Array
        (
            [country_percentage] => 0
        )

)

Comments

1

You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.

$array = [
    ["country_percentage" => "5 %North America"],
    ["country_percentage" => "0 %Latin America"]
];

array_walk_recursive($array, function(&$value,$key){
    $value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
    // or 
    $value = intval($value);
});

print_r($array);

Will output

Array
(
    [0] => Array
        (
            [country_percentage] => 5
        )

    [1] => Array
        (
            [country_percentage] => 0
        )

)

2 Comments

Alex Andrie 1 more Question please. Now, I extract string value from array and based on that string I show the numeric value. For Example:- if(string==North America){ echo 5 }.. Thanks in advance..
It seems you either need to work on constructing better the initial array to support the later queries on it, if not possible the construct a new one in the array_walk_recursive call, maybe using the continent names as keys and percentages as values. Then just echo $data[$continent];
1

You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.

// Array to hold just the numbers
$newArray = array();

// Loop through array
foreach ($array as $key => $value) {
    // Check if the value is numeric
    if (is_numeric($value)) {
        $newArray[$key] = $value;
    }
}

I missunderstood your question.

$newArray = array();
foreach ($array as $key => $value) {
    foreach ($value as $subkey => $subvalue) {
        $subvalue = trim(current(explode('%', $subvalue)));
        $newArray[$key] = array($subkey => $subvalue);
    }
}

2 Comments

1 more Question please. Now, how can I extract string value from array and based on that string I show the numeric value. For Example:- if(string==North America){ echo 5 }.. Thanks in advance..
In my above answer just replace current() with end() to get the string value
1

If you want all but numeric values :

$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) { 
       $newArray[][$key1] = intval($arr1);
  }
}
echo "<pre>";
print_R($newArray);

1 Comment

1 more Question please. Now, how can I extract string value from array and based on that string I show the numeric value. For Example:- if(string==North America){ echo 5 }.. Thanks in advance..
0

This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D

$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
  // IF Is numeric (each item from the array) will insert into new array called $new.
  if (is_numeric($item)) { array_push($new, $item); } 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.