Noobie
Noobie

Reputation: 99

Convert string values of associate array to integer

I got an array as follows.

I need to convert the values as integer

array:17 [
  0 => array:2 [
    "c" => "gmail"
    "co" => "12"
  ]
  1 => array:2 [
    "c" => "dddd"
    "co" => "2"
  ]
  2 => array:2 [
    "c" => "mmmmm"
    "co" => "2"
  ]
  3 => array:2 [
    "c" => "dsf"
    "co" => "2"
  ]
  4 => array:2 [
    "c" => "aaaa"
    "co" => "1"
  ]
  5 => array:2 [
    "c" => "bbbb"
    "co" => "1"
  ]
  6 => array:2 [
    "c" => "ccc"
    "co" => "1"
  ]
  7 => array:2 [
    "c" => "yopmail"
    "co" => "1"
  ]
  8 => array:2 [
    "c" => "yahoo"
    "co" => "1"
  ]
]

I need to convert all values of the key co to integer ,where currently they are string.

Is this is the way to use the foreach,which didn't give me correct output

 foreach($getDashboardDetails as $getDashboardDetails)
    {
        $getDashboardDetails['co']=(int)$getDashboardDetails['co'];
    }

Hope Someone can help

Upvotes: 0

Views: 62

Answers (3)

LahiruTM
LahiruTM

Reputation: 648

Use below code to get it, your foreach is in incorrect foam.

$new_array = array();
foreach($getDashboardDetails as $key=>$value)
{
    $new_array[$key]=array("c"=>$value['c'], "co"=>(int)$value['co']);
}

Now you have $new_array with expected results.

Upvotes: 1

René Beneš
René Beneš

Reputation: 468

I think the for loop is more what are you looking for as you want to change the initial array.

for($i=0;$i<=count($getDashboardDetails)-1;$i++) {
    $getDashboardDetails[$i]["co"] = (int)$getDashboardDetails[$i]["co"];
    $i++;
}

Or you can use foreach with a key-value pair on both dimensions, but I don't find it neccessary.

Upvotes: 1

lovelace
lovelace

Reputation: 1205

This might help you on your way(assuming $getDashboardDetails is the source array):

foreach($getDashboardDetails as $key => $value) {
    foreach($value as $key1 => $value1) {
        if ($key1 === "co") {
            $getDashboardDetails[$key][$key1] = (int)$getDashboardDetails[$key][$key1];
        }
    }
}

Upvotes: 1

Related Questions