Looping through difference sized arrays - avoiding 'Undefined offset' error

numpy iterate over 2d array
numpy iterate over rows with index
for loop python
fastest way to iterate through numpy array
nditer vs for loop
python vectorize for loop
fill numpy array in loop
how to iterate through a matrix in numpy

I'm working on a basic system to generate random word combinations.

I run one bit of SQL and get an array with results in, and another bit of SQL to get a 2nd array with a different set of words.

I loop through the first array, and join the first word from that with the corresponding word from the 2nd array.

Therefore, say I have these two arrays:

Array // referred to as `$list1

    [0] => yttrium
    [1] => yafty
    [2] => yard
    [3] => yellowknife
    [4] => yeasty
    [5] => york
    [6] => yo
    [7] => yemeles
    [8] => yo
    [9] => yellowstone

Array // referred to as `$list2

    [0] => yudding
    [1] => yudge
    [2] => yoody
    [3] => yeer
    [4] => yoisy
    [5] => yafty
    [6] => yine
    [7] => yuity
    [8] => yio

I loop through using this basic bit of code:

foreach ($list1 as $k => $v) {

    $words['output'][] = [
        'id' => $k,
        'value' => $v . '.' . $list2[$k]

Looking at the sample array above, the problem I have is if there are more elements in list1 compared to in list2 as I get this error:

Undefined offset: 9 in C:\xampp\public_html\test.php on line 224

Where line 224 is this one:

'value' => $v . '.' . $list2[$k]

I have been trying to work out how to get around this - for example - by counting the size of the arrays, and if list2 contains fewer elements than list1 then only loop through list1 as many times as there are elements in list2.

I was trying klunky solutions like:

$s1 = sizeof($list1);
$s2 = sizeof($list2);

if ($s2 < $s1) {
    $k = $s2;
} else {
    $k = $s1;

foreach ($list1 as $k => $v) {

    $words['output'][] = [
        'id' => $k,
        'value' => $v . '.' . $list2[$k]

However, that doesn't solve the problem.

You can use isset() to test if the array element exists.

'value' => $v . '.' . (isset($list2[$k]) ? $list2[$k] : "")

Your code isn't working because you're not actually using the value of $k that you set. You're just overwriting it with the keys of $list1. The right way to write your second loop is:

foreach (array_slice($list1, 0, $k) as $key => $value) {

BTW, there's a built-in function for finding the smaller number: $k = min($s1, $s2);

What are the different ways to iterate over an array in Java?, works 6 times slower on lists, comparing to arrays. Arrays Arrays and Loops Omit Array Size. You can loop through the array elements with the for loop. and examples are constantly reviewed to avoid errors, but

You could try only adding the element from the second array if it exists:

foreach ($list1 as $k => $v) {
    $value = $v;
    if (isset($list2[$k]) {
        $value .= '.' . $list2[$k];
    $words['output'][] = [
        'id' => $k,
        'value' => $value

NumPy - Iterating Over Array, The preferred idiom for iterating over collections and arrays for (Element e for (​int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ } calling next on iterator for LinkedList so you can avoid that performance hit while retaining  This array concatenates a string until it’s too big and adds it to the array once it’s big enough. In this formula, {YourValue} is the item that you’re looping through adding to the list. NOTE : For some reason, I couldn’t get Crystal to just end the if statement and execute the last line regardless, so I had to repeat it in an “else

Maybe use array_key_exists(value, array); to determine if the key exists in both arrays within your loop


if(array_key_exists($k, $list2)){
    Do something if exists
    If doesn’t exist do something 

Foreach or For, How to use loops to iterate over lists of data in computer programs. the array.​length property. i++ : This is executed after each iteration of the loop, In many languages, it causes a runtime error, preventing the rest of the code It looks very similar to the correct for loop from before, but there's one tiny but crucial difference. In the previous shell array post we discussed the declaration and dereferencing of arrays in shell scripts. This time we will take a look at the different ways of looping through an array. Setup This is the same setup as the previous post Let’s make a shell script. In your favourite editor type #!/bin/bash And…

Lists Part III: Lists vs Arrays - D. L. Jerome, If you've already mastered the basics of iterating through Python lists, take it to the next Regardless of these differences, looping over tuples is very similar to lists. If we try to iterate over a pandas DataFrame as we would a numpy array, this The key idea is to first calculate the length of the list and then iterate over the  If working with data is part of your daily job, you will likely run into situations where you realize you have to loop through a Pandas Dataframe and process each row. I recently find myself in

Is there a performance difference between a for loop and a for-each , an empty array of zeros that is the same size as the coordinate arrays, which will The operations in this loop all involve whole array objects, and so when we This is the advantage of using the NumPy arrays: it simplifies the code and avoids Accordingly delta is the array of all coordinate differences, and the elements  For data science and modern machine learning tasks, this is an invaluable advantage, as often the data set size runs into millions if not billions of records and you do not want to iterate over it using a for-loop along with its associated baggage.

Iterating over lists with loops, We can see this by iterating over the transpose of our previous array, compared to taking a By forcing 'C' and 'F' order, we get different external loop sizes. Let's start with a minimal function definition excluding 'out' parameter support. The reason 'readonly' is the default for input arrays is to prevent confusion about​  In general, vectorized array operations will often be one or two (or more) orders of magnitude faster than their pure Python equivalents, with the biggest impact [seen] in any kind of numerical computations. [ source] When looping over an array or any data structure in Python, there’s a lot of overhead involved.

  • What should the output be if there is not a corresponding word in the second array?
  • Thanks @Barmar - your advice helped me fix the issue. Thanks for the useful explanation and clarification.