0

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

5
  • why you didnt use foreach ? Commented Dec 3, 2019 at 11:30
  • you can use casting for 'co' in the array by (int) co Commented Dec 3, 2019 at 11:31
  • Have you tried anything by yourself, or made some research on possible solutions? Please post your efforts Commented Dec 3, 2019 at 11:32
  • The problem with your solution is that you can't use the same var name for the foreach item. Rename the variable after 'as' and use the renamed variable inside. Commented Dec 3, 2019 at 11:36
  • @RenéBeneš Tried..No change..:-( Commented Dec 3, 2019 at 11:42

3 Answers 3

1

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.

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

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.