1

I have var_dump() variable $fruit_array as below:

array (size=3)
  0 => 
    array (size=1)
      'fruit_id' => string '2' (length=1)
  1 => 
    array (size=1)
      'fruit_id' => string '1' (length=1)
  2 => 
    array (size=1)
      'fruit_id' => string '3' (length=1)

I need to rename fruit_id to id and convert array string value to integer, example result:

array (size=3)
  0 => 
    array (size=1)
      'id' => int 2
  1 => 
    array (size=1)
      'id' => int 1
  2 => 
    array (size=1)
      'id' => int 3

How can I do that ? thanks

3
  • 4
    you can't rename array keys. but you can create a new one, copy/change the value, then delete the original. Commented Jun 16, 2015 at 14:12
  • any reason why I can't rename array keys? Commented Jun 16, 2015 at 14:31
  • ask the php designers. Commented Jun 16, 2015 at 14:32

1 Answer 1

2

You can do something like this:

<?php
foreach ( $array as $k=>$v )
{
  $array[$k] ['id'] = intval( $array[$k] ['fruit_id'] );
  unset($array[$k]['fruit_id']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, this is what I need :), can you show another method using array_map() ?

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.