PHP Arrays · Chapter 8.5 · Utility Functions · Final
PHP Array Utility Functions
array_column · shuffle · json · compact · extract
PHP Array Utility Functions — Database-style column extraction, randomization, JSON conversion, और variable management। Chapter 8 का Final Sub-chapter।
columnDB-style extraction
JSONAPI data format
compactVariables → Array
extractArray → Variables
📋 इस Article में क्या-क्या है
- array_column() — Column Extract
- array_rand() — Random Keys
- shuffle() — Array Shuffle
- json_encode() — PHP → JSON
- json_decode() — JSON → PHP
- compact() — Variables → Array
- extract() — Array → Variables
- range() — Sequence बनाना
1
array_column() — एक Column निकालना
array array_column( array $array, int|string|null $column_key, int|string|null $index_key = null )
array_column() — BASIC EXAMPLES
<?php$users = [
["id" => 1, "naam" => "Rahul", "city" => "Delhi"],
["id" => 2, "naam" => "Priya", "city" => "Mumbai"],
["id" => 3, "naam" => "Amit", "city" => "Delhi"],
];
// सभी names निकालो
print_r(array_column($users, "naam"));
// [Rahul, Priya, Amit]
// सभी IDs निकालो
print_r(array_column($users, "id"));
// [1, 2, 3]
// Index key set करो — id को key बनाओ
print_r(array_column($users, "naam", "id"));
// [1=>"Rahul", 2=>"Priya", 3=>"Amit"]
// null column — पूरी rows, id indexed
print_r(array_column($users, null, "id"));
// [1=>[full row1], 2=>[full row2], 3=>[full row3]]
?>
array_column() — REAL WORLD EXAMPLES
<?php// DB results process करना
$products = [
["id" => 101, "name" => "PHP Book", "price" => 450],
["id" => 102, "name" => "Laravel", "price" => 799],
["id" => 103, "name" => "MySQL", "price" => 299],
];
// 1. सभी IDs — IN query के लिए
$ids = array_column($products, "id");
$sql = "SELECT * FROM orders WHERE product_id IN (" . implode(",", $ids) . ")";
// 2. Name dropdown के लिए
$nameOptions = array_column($products, "name", "id");
foreach ($nameOptions as $id => $name) {
echo "<option value='$id'>$name</option>\n";
}
// 3. Quick lookup by ID
$byId = array_column($products, null, "id");
echo $byId[102]["name"]; // Laravel (O(1) lookup!)
// 4. All prices sum
echo array_sum(array_column($products, "price")); // 1548
?>
💡 array_column + array_column(null, key) = Fast Lookup: Database results को ID-indexed करने के लिए array_column($rows, null, "id") — फिर $byId[42] से O(1) access। हर बार foreach loop से ढूँढने की ज़रूरत नहीं।
2
array_rand() और shuffle() — Randomization
array_rand() — EXAMPLES
<?php$fruits = ["Apple", "Mango", "Banana", "Orange", "Grapes"];
// 1 random key
$randKey = array_rand($fruits);
echo $fruits[$randKey]; // Random fruit
// 3 random keys
$randKeys = array_rand($fruits, 3);
foreach ($randKeys as $key) {
echo $fruits[$key] . "\n";
}
// Lucky Draw — winner चुनना
$participants = ["Rahul", "Priya", "Amit", "Neha", "Raj"];
$winnerKey = array_rand($participants);
echo "🏆 Winner: " . $participants[$winnerKey];
?>
shuffle() — Array को Randomly Reorder करना
<?php$cards = ["A", "2", "3", "4", "5", "J", "Q", "K"];
// shuffle — original modify होता है, keys reset होते हैं
shuffle($cards);
print_r($cards); // Random order
// Quiz — 10 questions में से 5 random
$allQuestions = range(1, 20); // Q1 to Q20
shuffle($allQuestions);
$quizQuestions = array_slice($allQuestions, 0, 5);
echo "Quiz: Q" . implode(", Q", $quizQuestions);
// Seat allocation — random
$students = ["Rahul", "Priya", "Amit", "Neha"];
shuffle($students);
foreach ($students as $seat => $student) {
echo "Seat " . ($seat+1) . ": $student\n";
}
?>
array_rand vs shuffle: array_rand() — original नहीं बदलता, random keys return करता है। shuffle() — original modify करता है, keys reset। Destructive है! Copy पर shuffle करना हो तो: $copy = $arr; shuffle($copy);
3
json_encode() और json_decode() — JSON Conversion
json_encode() — PHP → JSON
<?php$user = [
"id" => 1,
"naam" => "Rahul Kumar",
"email" => "rahul@gmail.com",
"skills" => ["PHP", "MySQL", "Laravel"],
"active" => true
];
// Basic encode
echo json_encode($user);
// {"id":1,"naam":"Rahul Kumar","email":"...","skills":["PHP","MySQL","Laravel"],"active":true}
// Pretty print — JSON_PRETTY_PRINT
echo json_encode($user, JSON_PRETTY_PRINT);
// Unicode characters (Hindi) — JSON_UNESCAPED_UNICODE
$data = ["naam" => "राहुल"];
echo json_encode($data); // {"naam":"\u0930\u093e\u0939\u0941\u0932"} — escaped
echo json_encode($data, JSON_UNESCAPED_UNICODE); // {"naam":"राहुल"} ✅
?>
json_decode() — JSON → PHP
<?php$jsonStr = '{"id":1,"naam":"Rahul","skills":["PHP","MySQL"]}';
// Default — stdClass object return करता है
$obj = json_decode($jsonStr);
echo $obj->naam; // Rahul
echo $obj->skills[0]; // PHP
// true — Associative Array (mostly preferred)
$arr = json_decode($jsonStr, true);
echo $arr["naam"]; // Rahul
echo $arr["skills"][1]; // MySQL
// Error check
$result = json_decode("invalid json", true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
?>
JSON — API Response बनाना
<?php// REST API response
header("Content-Type: application/json");
$response = [
"status" => "success",
"code" => 200,
"data" => [
"users" => [
["id" => 1, "naam" => "Rahul"],
["id" => 2, "naam" => "Priya"],
],
"total" => 2
],
"message" => "Users fetched successfully"
];
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
?>
⚠️ json_decode — हमेशा true pass करो: json_decode($json) stdClass object देता है। ज़्यादातर cases में json_decode($json, true) use करो — associative array मिलेगा जो arrays की तरह access होता है।
4
compact() और extract() — Variables ↔ Arrays
compact() — Variables → Array
<?php$naam = "Rahul";
$umar = 25;
$city = "Delhi";
$email = "rahul@gmail.com";
// compact — variable names string में pass करो
$user = compact("naam", "umar", "city", "email");
print_r($user);
// ["naam"=>"Rahul", "umar"=>25, "city"=>"Delhi", "email"=>"rahul@gmail.com"]
// Template data pass करना
function renderView($template, $data) {
extract($data); // $data array variables बन जाते हैं
include $template;
}
$pageTitle = "PHP Tutorial";
$content = "Welcome to PHP";
renderView("page.php", compact("pageTitle", "content"));
?>
extract() — Array → Variables
<?php$data = [
"naam" => "Priya",
"umar" => 22,
"city" => "Mumbai",
];
// extract — keys variables बन जाती हैं
extract($data);
echo $naam; // Priya
echo $umar; // 22
echo $city; // Mumbai
// EXTR_PREFIX_ALL — prefix से conflicts avoid
extract($data, EXTR_PREFIX_ALL, "user");
echo $user_naam; // Priya
echo $user_city; // Mumbai
?>
⚠️ extract() — User Input पर कभी मत use करो! अगर user-controlled array पर extract() use करो, attacker $_SESSION, $config जैसे important variables overwrite कर सकता है। हमेशा EXTR_PREFIX_ALL use करो या trusted data पर ही extract() लगाओ।
5
range() — Sequence Array बनाना
range() — EXAMPLES
<?php// Numbers
print_r(range(1, 5)); // [1, 2, 3, 4, 5]
print_r(range(0, 10, 2)); // [0, 2, 4, 6, 8, 10] (step 2)
print_r(range(10, 1, -1)); // [10,9,8,...1] (countdown)
// Letters
print_r(range("a", "e")); // [a, b, c, d, e]
print_r(range("A", "Z")); // [A, B, C, ..., Z]
// Real world uses
// Dropdown years
$years = range(2000, date("Y"));
foreach ($years as $year) {
echo "<option>$year</option>";
}
// Random test data
$nums = range(1, 100);
shuffle($nums);
$sample = array_slice($nums, 0, 10); // 10 random numbers
?>
🏆
Chapter 8 — Array Functions Complete Series!
✅ Chapter 8 — PHP Arrays Complete Series
Ch.8Indexed, Associative, Multidimensional ArraysOverview
8.1push, pop, shift, unshift, in_array, search, merge, slice, splice, keys, valuesAdd/Remove
8.2array_map, array_filter, array_reduce, array_unique, array_flipFunctional
8.3sort, rsort, asort, arsort, ksort, krsort, usort, uasort, uksortSorting
8.4count, sum, product, min, max, diff, intersect, chunk, combine, padMath & Sets
8.5array_column, array_rand, shuffle, json_encode, json_decode, compact, extract, rangeUtility
array_column(null, "id") — Fast O(1) lookup। DB results index करने के लिए।
shuffle() — Original modify। Copy पर करना हो तो पहले clone करो।
json_decode($json, true) — हमेशा true pass करो — array मिलेगा।
compact() — Template data pass करना। extract() — template के अंदर।
extract() — User input पर कभी नहीं! EXTR_PREFIX_ALL use करो।
🚀 Chapter 8 Arrays COMPLETE! अगला बड़ा topic: Chapter 9: PHP Loops — for, while, foreach, do-while, break, continue सब detail में।
✓
Quick Reference — Chapter 8.5
| Function | काम | Returns | Best Use |
|---|---|---|---|
| array_column() | एक column extract | array | DB results, dropdown |
| array_rand() | Random keys | int|array | Lucky draw, quiz |
| shuffle() | Random reorder | bool | Cards, questions |
| json_encode() | PHP → JSON string | string | API response |
| json_decode() | JSON string → PHP | mixed | API data parse |
| compact() | Variables → Array | array | Template data |
| extract() | Array → Variables | int | Template rendering |
| range() | Sequence array | array | Years dropdown, loops |