1

I have an associative array in which i want to add a new key-value pair to the existing . Here is my code

foreach($result['apiAvailableBuses'] as $value){
     if(strpos($value['fare'], ",")!== false){ 
       $fare=substr($value['fare'], 0, strpos($value['fare'], ","))." +";
     }
  else{ 
     $fare=$value['fare']."/-";
  }
   //add new key
   $result['apiAvailableBuses'][]['actualFare']=$fare;


}

But the print_r($result['apiAvailableBuses']['actualFare']) gives undefined error.

9
  • I don't see $fare defined, do you ? Commented Feb 22, 2016 at 13:59
  • Could you show us your full code? Is that [] intentional or did you miss it out in your print_r. Commented Feb 22, 2016 at 14:00
  • print_r($result['apiAvailableBuses']['actualFare']) show undefined because it's undefined, your defining $result['apiAvailableBuses'][0]['actualFare'] Commented Feb 22, 2016 at 14:02
  • @Script updated my question Commented Feb 22, 2016 at 14:04
  • @Daan ok how can i add new key value to $result['apiAvailableBuses'] this array? Commented Feb 22, 2016 at 14:05

1 Answer 1

1

Your code is not clear: you want an array with all values (as per foreachsuggests) or one only value (as per $result['apiAvailableBuses']['actualFare'] suggests)?

If you want an array with all the values, write in this way:

foreach( $result['apiAvailableBuses'] as $key => $value )
{
    if( strpos( $value['fare'], "," ) !== false )
    { 
        $fare = substr( $value['fare'], 0, strpos( $value['fare'], "," ) )." +";
    }
    else
    { 
        $fare = $value['fare'] . "/-";
    }
    // add new key
    $result['apiAvailableBuses'][$key]['actualFare'] = $fare;
}

In this way you will add $fare to same key of current $result element. Otherwise, you will append a new $result element.

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

1 Comment

I need the entire array with a new key actualFare and its value

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.