Skip to content

Latest commit

 

History

History
279 lines (200 loc) · 6.43 KB

File metadata and controls

279 lines (200 loc) · 6.43 KB

Arrays in PHP

PHP arrays are powerful data structures to store multiple values in a single variable.


Learning Objectives

  • Understand the difference between indexed and associative arrays and when to use each.
  • Access, modify, and traverse array elements, including nested arrays.
  • Apply common built-in array functions (count(), sort(), explode(), in_array(), etc.).
  • Handle arrays safely — validate keys, use strict comparisons, and never trust request data.

Indexed Arrays

An indexed array is an ordered collection where keys are integers starting from 0.

array.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Indexed Arrays</title>
</head>
<body>

<?php
$array1 = array(4, 5, 6, 7, 21, 34, 56, 77, 2);

echo $array1[1]; // Output: 5
echo "<br />";
echo $array1[0]; // Output: 4

// Modify array element
$array1[0] = 99;
echo "<br />";
echo $array1[0]; // Output: 99

// Array with mixed data
$array2 = array(88, "Rahul", "Jain", array("a", "b", "c"));

echo "<br />";
echo $array2[0]; // Output: 88
echo "<br />";
echo $array2[1] . " " . $array2[2]; // Output: Rahul Jain
echo "<br />";

// Nested array access
echo $array2[3][0]; // Output: a
echo "<br />";
echo $array2[3][1]; // Output: b
echo "<br />";
echo $array2[3][2]; // Output: c
echo "<br />";

// User info array
$user = array(1, "Rahul", "Jain", "rahul@armour.com", "password1");
echo $user[3]; // Output: rahul@armour.com
?>

</body>
</html>

Associative Arrays

An associative array uses named keys (strings) instead of numeric indexes.

associative_array.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Associative Arrays</title>
</head>
<body>

<?php
// Normal indexed array
$user = array(1, "Rahul", "Jain", "rahul@armour.com", "password1");
print_r($user);
echo "<br />" . $user[3] . "<br />";

// Associative array
$user2 = array(
    'id' => 1,
    'f_name' => "Rahul",
    'l_name' => "Jain",
    'email' => "rahul@armour.com",
    'password' => "password1"
);

print_r($user2);
echo "<br />" . $user2['email'] . "<br />";
echo $user2['password'] . "<br />";

// Combining values
$user_full_name = $user2["f_name"] . " " . $user2["l_name"];
echo $user_full_name . "<br />";
$user_email = $user2["email"];
echo $user_email;
?>

</body>
</html>

Array Functions

PHP provides many built-in functions to work with arrays.

array_functions.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Array Functions</title>
</head>
<body>

<?php
$array1 = array(41, 34, 2, 35, 12, 65, 8, 9, 45);
?>

Count: <?= count($array1); ?> <br />
Max value: <?= max($array1); ?> <br />
Min value: <?= min($array1); ?> <br />

<?php
print_r($array1);
?>

<br />

Sort:
<?php  
sort($array1);
print_r($array1);
?>
<br />

Reverse Sort:
<?php  
rsort($array1);
print_r($array1);
?>
<br />

Explode:
<?php
$str3 = "This is a demo";
$array3 = explode(" ", $str3);
print_r($array3);
?>
<br />

Implode (space):
<?php
$str1 = implode(" ", $array1);
echo $str1;
?>
<br />

Implode (comma):
<?php
$str2 = implode(",", $array1);
echo $str2;
?>
<br />

In Array (check if 45 exists):
<?php
$int1 = in_array(45, $array1);
echo $int1 ? "Found" : "Not Found";
echo "<br />";
echo gettype($int1); // boolean
?>

</body>
</html>

Key Notes

Function Description
count() Count number of elements in an array
max() Find maximum value
min() Find minimum value
sort() Sort an array (ascending)
rsort() Sort an array (descending)
explode() Split a string into an array
implode() Join array elements into a string
in_array() Check if a value exists in an array

Best Practices

  • Always validate array keys before accessing them to avoid warnings.

  • Use associative arrays when working with structured data (like user records).

  • Prefer using array functions for better performance and cleaner code.


Quick Tip

When working with arrays:

  • print_r($array); is great for quick debugging.

  • var_dump($array); gives detailed type and value information.


Common Mistakes

  • Accessing an undefined key (e.g. $array[10] when it does not exist) raises a warning in PHP 8+. Guard with isset() or array_key_exists() first.

  • Assuming sort() preserves keys — sort() and rsort() reindex the array. Use asort() / ksort() when you need to keep associative key–value pairs aligned.

  • Relying on the default loose comparison of in_array()in_array(0, ["abc"]) returns true due to type juggling. Pass true as the third argument for strict matching.


Security Considerations

  • Never store secrets in plaintext — the example arrays above use 'password' => "password1" for illustration only. Real credentials must be hashed with password_hash() before storage and verified with password_verify().

  • Treat request data as untrusted — values from $_GET, $_POST, or $_REQUEST used as array keys or values should be validated and sanitized before use to avoid injection and logic-abuse bugs.

  • Use strict in_array() checks on security-relevant lookups (allowlists, role checks): in_array($needle, $haystack, true) prevents type-juggling bypasses.

  • Do not concatenate array data into SQL — when array values reach a database, always bind them through PDO prepared statements rather than building query strings.


Summary

  • Indexed arrays use integer keys starting at 0; associative arrays use named string keys for structured data.
  • Arrays can nest, letting you model records and collections in a single variable.
  • Built-in functions cover most needs — counting, sorting, splitting/joining, and membership tests.
  • Treat array data as untrusted where it comes from user input: validate keys, use strict in_array(), hash secrets, and bind values through PDO prepared statements before they reach SQL.

Related Topics

  • Multidimensional Arrays

  • Array Iteration (foreach, for, etc.)

  • Advanced Array Functions (array_map(), array_filter(), array_reduce())

Related