0

I need to loop over the following array but we can assume that the array can be empty in some cases:

Array
    (
    [0] => Array
        (
            [AA562-FS] => 521502151
        )

    [1] => Array
        (
            [FF-25166] => 66326262
        )
)

The first value is an ID and the other one is a number, I have an input of these two from another source, I need to loop over the array and if the ID is equal to the one i have from another source and its value the number is not equal to the one from the source i need to replace the number.

Otherwise I just add on to the existing array, but im having some issues right now, this is what i have so far:

 public function addToken($array1, $source_id, $source_number)
{
    if (!empty($array1)) {
        foreach ($array1 as $array) {
            if ($array[0] == $source_id && $array[1] !== $source_number) {
                $array1[1] = $source_number;
            }
        }
    }
    $new_array = json_encode($array1, 1);
}

Still need to figure out how to add on the values if its not equal $array[0] !== $source_id

Would it be better to build the array as following?

Array
    (
    [0] => Array
        (
            [id] => AA562-FS
            [number] => 521502151
        )

    [1] => Array
        (
            [id] => AAAD-wwww
            [number] => 1166777
        )
)

3 Answers 3

1

You're overcomplicating the array structure. You should build your array like this.

Array
(
        [AA562-FS] => 521502151
        [FF-25166] => 66326262
) 

This simplifies the code you need to update it:

 public function addToken($array1, $source_id, $source_number)
{
    // Assign the source number to the array element. 
    // If the array element does not exist it's created.
    // If it does exist, the source number is updated. 
    // (If the number is the same it's updated to the same number - OK!)

    $array1[$source_id] = $source_number;
    return $array1;
}
Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much for the input, it seems to work fine but in the case where i recieve a different $source_id it seems to not add it on to the existing array :(
I set exactly this code up on my test server, apart from two changes: remove the public keyword; add the ; after return $array1 (typo corrected here already). It works exactly as I expected it to, including creating new elements. I suspect the problem is somewhere else in your code.
what in the case that I have multiple data in the array? will it correspond to the correct one?
If you've built your array this way you won't have duplicate values. If you built the array you originally suggested you could have duplicates, but you'd also have no way to distinguish between them. You'd always update the first value you found, or you'd update all of them to be the same. If duplicates are an issue you need to provide more detail on exactly how this data is made up.
0

You can use a foreach ($array as $index => $value) loop, using the first array format you wrote. It will iterate on each element of your array, and in each iteration, the $index variable will correspond to your 'ID', and the $value variable to the value.

In your case it would look like this :

foreach ($array1 as $index => $value) {
    if ($index == $source_id && $value !== $source_number) {
        $array1[$index] = $source_number;
    }
}

Edit : if you want to add the value $source_number to the key $source_id in your array if it does not exists, the following function should do the trick :

public function addToken($array1, $source_id, $source_number)
{
    if (!empty($array1)) {
        foreach ($array1 as $index => $value) {
            if ($index == $source_id && $value !== $source_number) {
                $array1[$index] = $source_number;
            }
        }
        /* After you looped through your array, 
         * check if the id $source_id exists or not, and if not, 
         * insert it in your array:
         */
        if (!array_key_exists($source_id, $array1)) {
            $array1[$source_id] = $source_number;
        }
    }
    $new_array = json_encode($array1, 1);
}

9 Comments

thanks for the input! if the condition is not met do i just add on to the array assuming that the source_id does not exsist?
The code above will just replace the value for the element of your array that has $source_id for 'ID'. The result will be exactly your first array, but with the value $source_number associated with the ID $source_id (if it was not already the case). I cannot clearly understand why you would need to add to the array, as the array you will get as a result is the same you had in the beginning, and all you did was "replace" the value not corresponding to your condition.
if in the array the $source_id does not exist just add it on to the array, if it does it needs to replace the $source_number in the existing array; dont know if im making sense :D
I see, what you could do in this case is to add some code after your foreach loop to check if the ID exists as an array key in your array, using the PHP function array_key_exists($source_id, $array1) (see php.net/manual/en/function.array-key-exists.php for more info on this function). You could then do an if statement where you would add the value to the array with the $source_id if the function array_key_exists returns false (so the key does not exist). It would look like "if (!array_key_exists($source_id, $array1)) { $array1[$source_id] = $source_number }" (sorry for the edits).
I just edited my answer so it will be (I hope) clearer for you :)
|
0

Firstly, I'm assuming that you are passing in the array shown at the top of your question. Which will therefore be in the form:

$array = [
    ['AA' => 111],
    ['AB' => 111],
    ['AC' => 111],
    ['AD' => 111],
    ['AE' => 111],
    ['AA' => 112]
];

Assuming that that is correct then your if statement does not work:

$array[0] == $source_id && $array[1] !== $source_number

// $array[0] && $array[1] simply don't exist! Referencing them should
// throw a notice in PHP...


// In the first foreach loop $array looks as follows

$array = ['AA' => 111];

// In the second loop it will be

$array = ['AB' => 111];

// and so on through the array. The index, in this case, is AA, AB, AC etc.
// the indexes 0 and 1 just don't exist

That being the case we can begin to fix your code by modifying the if statement to:

key($array) == $source_id && current($array) !== $source_number

Of course we also need to update these two lines:

foreach ($array1 as $array)

$array1[1] = $source_number;

To:

foreach ($array1 as &$array)

$array = [$source_id => $source_number];

So, your code is now partially working; if we call the function it will update existing ID values however it won't add new ones...

// Notice we pass $array by reference( & ) so that it updates the original array
// if you prefer not to do this then, obviously, you need to return the updated array

function addToken(&$array, $source_id, $source_number)
{
    if (!empty($array)) {
        foreach ($array as &$arr) {
            if(key($arr) == $source_id && current($arr) != $source_number) {
                $arr = [$source_id => $source_number];
            }
        }
    }
}

addToken($array, "AB", 112);

// Updated array...
$array = [
    ['AA' => 111],
    ['AB' => 112],
    ['AC' => 111],
    ['AD' => 111],
    ['AE' => 111],
    ['AA' => 112]
];

Adding an item if it doesn't exist

To do this we need to firstly look though the entire array to see if there is a match and if there isn't, at the end, then we add a new item.

function addToken(&$array, $source_id, $source_number)
{
    if(!empty($array)){
        $tokenExists = false;
        foreach($array as &$arr){
            if(key($arr) == $source_id){
                $arr = [$source_id => $source_number];
                $tokenExists = true;
            }
        }

        if(!$tokenExists){
            $array[] = [$source_id => $source_number];
        }
    }
}

Notice, we don't need to check whether the value matches $source_number, we just update the value to $source_number either way we have the same result.


However unless you have duplicates in your input array (as shown, purposefully in the example I've used above) where an ID in the original array could have multiple values that all need to be updated to the new one. There is no need for any of this @TP has the right idea!

Simplify the format to:

$array = [
    'AA' => 111, // Note this value is effectively overwritten by the last line of the arrray, you can't have duplicate keys
    'AB' => 111,
    'AC' => 111,
    'AD' => 111,
    'AE' => 111,
    'AA' => 112
];

function addToken(&$array, $source_id, $source_number)
{
    $array[$source_id] = $source_number;
}

Although, with this simplified array... Do you even need to put the update in a function/method? I guess that depends on the rest of your code.

1 Comment

thank you so much for the indepth answer, this makes this so much more cleaner in my head, i was totally overcomplecating this whole situtation :)

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.