简体   繁体   中英

php- popping a value from array returns wrong result

Ok, I will explain what I am trying to implement here. It's like a number search. I will pass a number and server returns an array of all number. If the passed number is present, I will have to pop that number from the array.

It works, but not in all scenarios.

<?php

function fetchAll()
{
    $data= array();
    $motherArray='["1","48","2","44","4"]';
    $data       =   json_decode($motherArray); 
    return $data;
}

$allIDs=fetchAll();
if (!empty($allIDs)) 
{
    $checkThis=4;
    if(in_array($checkThis,$allIDs))
    {
        if (($key = array_search($checkThis, $allIDs)) !== false) 
        {
            unset($allIDs[$key]);
        }       
        if(!empty($allIDs))
        {       
            $allIDsJSON         = json_encode($allIDs);
            echo $allIDsJSON;
        }
        else
        {
            echo 'empty';
        }           
    }
    else
    {
        echo 'not present';
    }
}

?>

Above given is my code. I'm trying to search for the number 4.

Number 4 can be in any position. It can be in first, middle or the last. My code works if the number is in last position. Then, it returns the correct output.

Case 1 :

$motherArray='["1","48","2","44","4"]';

if it is in last position, I get the correct output:

["1","48","2","44"]

Case 2 :

If number 4 is in any other position

$motherArray='["1","48","2","4","44"]';

then the output I get is:

{"0":"1","1":"48","2":"2","4":"44"}

I don't know why it is happening like that. Can anyone help me figure out what's wrong with this code?

如果您的号码有多个值,那么您的代码将无效:

foreach (array_keys($allIDs, $checkThis) as $key) unset($allIDs[$key]);

The correct answer is provided in the comments already.I will just add it here with some explanation.

If number is not in last position then when you unset($allIDs[$key]); you create an array that is not sequential.

Original array: Array ( [0] => 1 [1] => 48 [2] => 2 [3] => 4 [4] => 44 )

Array after unsetting third element: Array ( [0] => 1 [1] => 48 [2] => 2 [4] => 44 )

Because in javascript there are not associative arrays when you use json_encode($allIDs); the valid JSON result you get is a JSON object not an array.

So if you want an array you have to reindex the array yourself like that:

$indexed_array = array();

foreach ($allIDs as $row) {
    $indexed_array[] = $row;
}

json_encode($indexed_array);

Or by using array_values function

echo json_encode(array_values($allIDs))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM