1
$number_array = array();

//in a while loop

//part of code
if(array_key_exists($read_num, $number_array))
{
        $arr[$read_num][A] .= $new_A;
}
else
{
$inner_arr = array( "$read_num" => array( "id"=>$read_num, "A"=>$new_A ) );
$number_array = array_push($number_array,$inner_arr);

unset($inner_arr);
}

I get error like:

Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in try.php on line 24
Warning: array_push() [function.array-push]: First argument should be an array in try.php on line 33

I declare an empty array outside of the while loop

$number_array = array();

what did i do wrong here that cause the error to appear

EDIT:

I have this value when I did the code above

Array
(
[0] => Array
    (
        [0011] => Array
            (
                [id] => 0011
                [A] => 2.50
                [B] => 2.00
                [C] => 5.40
            )

    )

[1] => Array
    (
        [0017] => Array
            (
                [id] => 0017
                [A] => 5.00
                [B] => 0.00
                [C] => 8.00
            )

    )

[2] => Array
    (
        [0022] => Array
            (
                [id] => 0022
                [A] => 1.00
                [B] => 0.00
                [C] => 1.60
            )

    )

How do I remove the [0] , [1] and [2] and make it as [0011] , [0017], [0022] so my array key exists can work

1
  • Don't make stealth edit's! If you changed your question or appended a new one please mark it with: EDIT: Commented Dec 16, 2014 at 18:26

1 Answer 1

4

It's because you re-assign the return value of array_push to $number_array

$number_array = array_push($number_array,$inner_arr);

remove it :

array_push($number_array,$inner_arr);

Because array_push return new number of elements in the array not the array itself.

Alternatively you can just write:

$number_array[] = $inner_arr;

It's the same thing.

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

2 Comments

Hi thanks for the solution, may I ask if I want to array_push index to a certain key e.g $number_array[$number] , how do I achieve it. because I tried array_push and it insert int sequence [0] > [1] then 2 etc..
@NormaHoliga then use the second option I gave you $number_array[$index] = $inner_arr;

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.