Skip to content

Instantly share code, notes, and snippets.

@huzoorbux
Created November 5, 2023 05:20
Show Gist options
  • Save huzoorbux/73066e2bcd3b5fab6aa253263b9d91cc to your computer and use it in GitHub Desktop.
Save huzoorbux/73066e2bcd3b5fab6aa253263b9d91cc to your computer and use it in GitHub Desktop.
Array Exercises (PHP)

Array Exercises (PHP)

Questions

  1. If you have an array $a = array( 0, 1, 2, 3, 4 );, how do you extract the value 3 from the array?

  2. If you have an array $a = array( "zero"=>0, "one"=>1, "two"=>2, "three"=>3, "four"=>4 );, how do you extract the value 3 from the array?

  3. If you have the following array, how do you extract the value 3 from the array?

    $a = array(
        array(
            0,
            1
        ),
        array(
            2,
            array(
                3
            )
        )
    );
    
  4. If you have the following array, how do you extract the value 3 from the array?

    $a = array(
        "a"=>array(
            "b"=>0,
            "c=>1
        ),
        "b"=>array(
            "e"=>2,
            "o"=>array(
                "b"=>3
            )
        )
    );
    
  5. Create a new array with each comma-separated value as its own array element from the string $a = "a,b,c,d,e,f".

  6. With the result array from 5, create a new array where each element is both key and value. In other words, the result should be:

    array(
        "a"=>"a",
        "b"=>"b",
        "c"=>"c",
        "d"=>"d",
        "e"=>"e"
    )
    
  7. You have two arrays like the following. One contains field labels, the other contains field values. Write a program to output the third array.

    $keys = array(
        "field1"=>"first",
        "field2"=>"second",
        "field3"=>"third"
    );
    $values = array(
        "field1value"=>"dinosaur",
        "field2value"=>"pig",
        "field3value"=>"platypus"
    );
    // want to output
    $keysAndValues = array(
        "first"=>"dinosaur",
        "second"=>"pig",
        "third"=>"platypus"
    );
    
  8. You have an array of transactions, each of which has a debit and credit amount. Find the absolute value of the transaction amount (i.e. abs( debit - credit )) and add it as a new key=>value pair to each transaction.

    $transactions = array(
        array(
            "debit"=>2,
            "credit"=>3
        ),
        array(
            "debit"=>15,
            "credit"=>14
        )
    );
    // outputs
    $transactions = array(
        array(
            "debit"=>2,
            "credit"=>3,
            "amount"=>1
        ),
        array(
            "debit"=>15,
            "credit"=>14,
            "amount"=>1
        )
    );
    
  9. Find the sum of this array of numbers $a = array( 0, 1, 2, 3, 4, 5, 6 );.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment