John Davidson

PHP associative array foreach

0 comments
Message:


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
)
)


My Answer:
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);

foreach ($array as $key => $value) {
echo $key . ": " . $value . "
";
}

This code will loop over the associative array and print out each key and its corresponding value. If the array is empty, the loop will not execute and nothing will be printed.

Rate this post

5 of 5 based on 7543 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us