Get only Numeric values from Array in PHP - php

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...

When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}

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'] );
}
}

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);
}

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
)
)

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
)
)

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);
}
}

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);

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); }
}

Related

Convert Indexed Array to Associate Array with Indexed Exploded Values

Having issues converting an array like this into an associative array
$array =
Array
(
[0] => 154654654455|WS01
[1] => 456541232132|WS02
)
Into an associative array.
I can do a foreach loop and explode the values
$values2 = array();
foreach ($array as $key => $value) {
$values2[] = explode("|",$value);
}
But then I get something like this
Array
(
[0] => Array
(
[0] => 154654654455
[1] => WS01
)
[1] => Array
(
[0] => 456541232132
[1] => WS02
)
)
What's the best way to convert something like this into an associative array like such
Array
(
[154654654455] => WS01
[456541232132] => WS02
)
$values2 = array();
foreach ($array as $key => $value) {
$expl = explode("|",$value);
$values2[$expl[0]] = $expl[1];
}
Probably not the most elegant way, but modifying your approach it would be:
$values2 = array();
foreach ($array as $key => $value) {
$t = explode("|",$value);
$values2[$t[0]] = $t[1];
}
change your foreach loop to this
foreach ($array as $key => $value) {
$temp = explode("|",$value);
$values2[$temp[0]] = $temp[1];
}
All you need to do is to set the the first item of the explode as key and the second as value:
$array = [
'154654654455|WS01',
'456541232132|WS02',
];
$values2 = [];
foreach ($array as $key => $value) {
$data = explode('|', $value);
$values2[$data[0]] = $data[1];
}
Demo: https://3v4l.org/cEJE5
Not the best answer, but for completeness; after your loop you can extract the 1 column as values and index on the 0 column:
$values2 = array_column($values2, 1, 0);
I am going to put the exact same answer here as everyone else,but I will omit the unused $key variable...
$val2 = array();
foreach ($array as $v) {
$tmp = explode("|",$v);
$val2[$tmp[0]] = $tmp[1];
}

Convert a one dimensional array to two dimensional array

I have an array, whose structure is basically like this:
array('id,"1"', 'name,"abcd"', 'age,"30"')
I want to convert it into a two dimensional array, which has each element as key -> value:
array(array(id,1),array(name,abcd),array(age,30))
Any advice would be appreciated!
I tried this code:
foreach ($datatest as $lines => $value){
$tok = explode(',',$value);
$arrayoutput[$tok[0]][$tok[1]] = $value;
}
but it didn't work.
Assuming you want to remove all quotation marks as per your question:
$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}
You can do something like this:
$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
$temp = explode("," $first_array);
$b[$temp[0]] = $b[$temp[1]];
}
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
$val[] = array($aa);
}
print_r($val);
Output:
Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )
With array_map function:
$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
list($k,$v) = explode(',', $v);
return [$k => $v];
}, $arr);
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => "1"
)
[1] => Array
(
[name] => "abcd"
)
[2] => Array
(
[age] => "30"
)
)

transfer specific index of array to a new array - php

I want to delete an index from array and insert it into in new array. I want two things which i tried to explain one is
Array
(
[index1] => Deleted
[index4] => Inserted
)
Array
(
[index3] => test
[index4] => Inserted
)
Array
(
[index2] => numbers
[index3] => test
[index4] => Inserted
)
Array
(
[index1] => Deleted
)
now i want if arraysize is 1
foreach($array as $arrays){
array_push($array1,($arrays[0]));
unset ($arrays[0]);
}
i want to remove
Array
(
[index1] => Deleted
)
from $array and $array to be
[index1] => Deleted
second is if $array is
Array
(
[index2_123] => numbers
[index3_level] => test
[index4_test] => Inserted
)
i want a new array with $array1 as
Array
(
[index3_level] => test
)
and $array1 is modified to
Array
(
[index2_123] => numbers
[index4_test] => Inserted
)
Try this way,
$arr = Array
(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted'
);
$arr1 = $arr2 = array();
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr1[$key] = $value;
}else{
$arr2[$key] = $value;
}
$i++;
}
Output
$arr1
Array
(
[index1] => Deleted
[index3] => test
)
$arr2
Array
(
[index2] => numbers
[index4] => Inserted
)
And if you don't need that value then you can use it as
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr[$key] = $value;
}else{
unset($arr[$key]);
}
$i++;
}
print_r($arr);
Output:
Array
(
[index1] => Deleted
[index3] => test
)
Loop through them and generate the array -
$new = array();
foreach($yourarray as $key => $val) {
$index = str_replace('index', '', $key); // get the key index
if($index % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
}
Update
For any index use a counter
$i = 0;
$new = array();
foreach($yourarray as $key => $val) {
if($i % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
$i++;
}
You can use a combination of array_flip and array_diff_key to filter the first array, then use array_diff filter the second:
$specificIndex = array('index1', 'index3');
$array1 = array_diff_key($array, array_flip($specificIndex));
$array2 = array_diff($array, $array1);
Demo.
If you want get in an array only certain elements of your choice you can do something like:
$specificIndex = array('index1', 'index3');
$selectedItem = array_intersect_key($array, array_flip($specificIndex));
Demo.
<?php
$array = array(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted',
);
$specificIndex = 'index3';
$array1=array();
foreach($array as $key => $value){
if($key==$specificIndex){
$array1[$key] = $value;
unset($array[$specificIndex]);
}
}
print_r($array);
print_r($array1);
http://3v4l.org/TvZ19

Don't want Array ito combine values

I Have an array in PHP that looks like:
Array ( [2099:360] => 6-3.25 [2130:361] => 4-2.5 [2099:362] => 14-8.75 )
Notice there is Two Keys that are 2099 and one that is 2130. I Have a foreach to remove the everything after the colon. the $drop is my array
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
$a[$ex_part[0]] = $drop_a;
}
print_r($a);
but when I print $a it displays only the recent value of the 2099?
Array ( [2099] => 14-8.75 [2130] => 4-2.5 )
Any Successions? How can I get it to display all of the values?
Thank You for Your Help
One solution is to use a multi-dimensional array to store this strategy:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][] = $drop_a;
} else {
$a[$ex_part[0]] = array($drop_a);
}
}
Your resulting data-set will however be different:
Array ( [2099] => Array ( [0] => 6-3.25 [1] => 14-8.75) [2130] => Array ( [0] => 4-2.5 ) )
It may be beneficial to you to preserve the second portion after the colon :
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][$ex_part[1]] = $drop_a;
} else {
$a[$ex_part[0]] = array($ex_part[1] => $drop_a);
}
}
Now your result is a little more meaningful:
Array ( [2099] => Array ( [360] => 6-3.25 [362] => 14-8.75) [2130] => Array ( [361] => 4-2.5 ) )
Finally you can use alternative key-naming strategy if one is already occupied:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[altName($ex_part[0], $a)] = $drop_a;
} else {
$a[$ex_part[0]] = $drop_a;
}
}
function altName($key, $array) {
$key++; // Or however you want to do an alternative naming strategy
if (isset($array[$key])) {
return altName($key, $array); // This will eventually resolve - but be careful with the recursion
}
return $key;
}
Returns:
Array
(
[2099] => 6-3.25
[2130] => 4-2.5
[2100] => 14-8.75
)
You basically have a key and a sub key for each entry, so just put them in a multidimensional array:
$a = array();
foreach ($drop as $key => $val) {
list($key, $subKey) = explode(':', $key);
$a[$key][$subKey] = $val;
}
Gives you:
Array
(
[2099] => Array
(
[360] => 6-3.25
[362] => 14-8.75
)
[2130] => Array
(
[361] => 4-2.5
)
)
You can traverse multidimensional arrays by nesting loops:
foreach ($a as $key => $subKeys) {
foreach ($subKeys as $subKey => $val) {
echo "$key contains $subKey (value of $val) <br>";
}
}

need to search for values in each string of an array to construct another array

I have this array:
Array
(
[count] => 12
[6] => CN=G_Information_Services,CN=Users,DC=hccc,DC=campus
[7] => CN=WEBadmin,CN=Users,DC=hccc,DC=campus
[9] => CN=G_ISDept,CN=Users,DC=hccc,DC=campus
[10] => CN=STAFF,CN=Users,DC=hccc,DC=campus
)
and I want to create an array of values that consist of the value between the first CN= and , of each array value below.
I probably will have to loop thru the array above, do a regex search for the first occurrence of cn and the value that follows it
I am not sure what I am doing wrong.
I need the final result to be an array that resembles this:
array('G_Information_Services', 'WEBadmin', 'G_ISDept', 'STAFF');
Use preg_match on each of the array values to get only the first corresponding CN value.
$found = array();
foreach ($arr AS $values) {
if (preg_match('/CN=([^,]+),/',$values,$matches))
$found[] = $matches[1];
}
Output
Array
(
[0] => G_Information_Services
[1] => WEBadmin
[2] => G_ISDept
[3] => STAFF
)
Try this (not the most efficient way but it should work):
foreach ($array as $key => $value)
{
if (is_numeric($key))
{
$array[$key] = explode(',', $array[$key]);
$array[$key] = $array[$key][0];
$array[$key] = substr($array[$key], 3);
}
}
This gets the first value of CN= of each element of the array, it also ignores any DC= values.
$arr = array(
'count' => 12,
6 => 'CN=G_Information_Services,CN=Users,DC=hccc,DC=campus',
7 => 'CN=WEBadmin,CN=Users,DC=hccc,DC=campus',
9 => 'CN=G_ISDept,CN=Users,DC=hccc,DC=campus',
10 => 'CN=STAFF,CN=Users,DC=hccc,DC=campus'
);
$newArr = array();
foreach($arr as $key => $value)
{
if($key != 'count')
{
$temp = explode(',', $value);
foreach($temp as $item)
{
if(strpos($item, 'CN=') === 0)
{
$item = substr($item, 3 );
$newArr[] = $item;
break 1;
}
}
}
}
print_r($newArr);

Categories