Arrays & String Functions
Learn key PHP array and string manipulation methods. Essential for sorting, filtering, merging, and text processing in technical interviews.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What are the most commonly used array functions in PHP?
PHP has over 80 built-in array functions. These are the ones that come up most in day-to-day code and interviews.
| Function | Purpose |
|---|---|
| count() | Number of elements in an array |
| array_push() / array_pop() | Add / remove from the end |
| array_shift() / array_unshift() | Remove / add from the beginning |
| array_slice() | Extract a portion of an array |
| array_splice() | Remove/replace a portion, modifies original array |
| array_keys() / array_values() | Get all keys / all values |
| array_reverse() | Reverse element order |
| array_flip() | Swap keys and values |
Interview tip: Know the difference between array_slice() (returns a new array, non-destructive) and array_splice() (modifies the original array in place) - a frequent follow-up.
Q2. What is the difference between array_map, array_filter, and array_reduce?
All three take a callback and an array, but they do fundamentally different things.
| Function | Purpose | Returns |
|---|---|---|
| array_map() | Transforms every element | New array, same length |
| array_filter() | Keeps elements matching a condition | New array, possibly shorter, keys preserved |
| array_reduce() | Combines all elements into a single value | A single value (not an array) |
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
// [2, 4, 6, 8, 10]
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [1 => 2, 3 => 4]
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
// 15Interview tip: Point out that array_filter() preserves original keys - a common gotcha when the result is later re-indexed with array_values() before use in a foreach expecting sequential keys.
Q3. How do you sort arrays in PHP? Explain sort, ksort, and usort.
Short Answer
Indexed Arrays use numeric keys (starting from 0 by default) to store and access data.
Associative Arrays use named string keys that you define to store and access data, acting like dictionaries or hash maps.
Detailed Explanation & Code Example
1. Indexed Arrays
Best used when you have a simple list of items where the order matters, but you don't need to assign specific labels to them.
$colors = ["Red", "Green", "Blue"];
// Accessing data requires knowing its numeric index
echo $colors[0]; // Outputs: Red
echo $colors[2]; // Outputs: Blue
// Adding a new item automatically assigns the next index (3)
$colors[] = "Yellow";
2. Associative Arrays
Best used when you want to map a specific key to a specific value, making the code highly readable and organized.
$user = [
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
];
// Accessing data is intuitive using the string key
echo $user["first_name"]; // Outputs: John
echo $user["age"]; // Outputs: 30
// Adding a new item
$user["role"] = "Admin";
Q4. What is the difference between explode() and implode() in PHP?
explode() splits a string into an array using a delimiter. implode() (alias: join()) joins array elements into a single string using a glue string. They are exact opposites.
$csv = 'Raj,Amit,Sara';
$names = explode(',', $csv);
// ['Raj', 'Amit', 'Sara']
$joined = implode(' | ', $names);
// 'Raj | Amit | Sara'| Function | Direction | Signature |
|---|---|---|
| explode() | string to array | explode(separator, string, limit) |
| implode() | array to string | implode(glue, array) |
Interview tip: Mention the optional third 'limit' parameter of explode() - a positive limit caps the number of pieces, and a negative limit removes that many elements from the end.
Q5. What is the difference between array_merge() and the + operator for combining arrays?
Both combine two arrays, but they handle duplicate keys very differently.
| Aspect | array_merge() | + operator |
|---|---|---|
| String keys, duplicate | Later array's value overwrites earlier | Earlier (left) array's value wins |
| Integer keys | Re-indexed sequentially | Original integer keys preserved |
$a = ['name' => 'Raj', 0 => 'x'];
$b = ['name' => 'Amit', 0 => 'y'];
print_r(array_merge($a, $b));
// ['name' => 'Amit', 0 => 'x', 1 => 'y'] -- b overwrites, ints re-indexed
print_r($a + $b);
// ['name' => 'Raj', 0 => 'x'] -- a wins, int keys preservedInterview tip: This is a classic trick question because the results are opposite for string keys - always test with a concrete example when explaining, don't just state the rule.
Q6. What are the most useful PHP string functions? (strlen, substr, str_replace, trim)
| Function | Purpose | Example |
|---|---|---|
| strlen($str) | Get string length in bytes | strlen('Hello') = 5 |
| substr($str, $start, $len) | Extract a portion of a string | substr('Hello', 1, 3) = 'ell' |
| str_replace($search, $replace, $str) | Replace occurrences of a substring | str_replace('a', '@', 'banana') = 'b@n@n@' |
| trim($str) | Remove whitespace (or given chars) from both ends | trim(' hi ') = 'hi' |
| strtolower / strtoupper | Change case | strtoupper('hi') = 'HI' |
| str_contains($haystack, $needle) | Check if a string contains a substring (PHP 8+) | str_contains('Hello', 'ell') = true |
Interview tip: Mention that PHP strings are byte-based, so strlen() and substr() can misbehave on multi-byte (UTF-8) text like Hindi - use mb_strlen() and mb_substr() for correct multi-byte handling.
Q7. What is the difference between strpos() and stripos()?
Both find the position of the first occurrence of a substring within a string. The only difference is case sensitivity.
| Function | Case sensitive? |
|---|---|
| strpos() | Yes |
| stripos() | No (case-insensitive) |
strpos('Hello World', 'world'); // false, case mismatch
stripos('Hello World', 'world'); // 6, found ignoring caseInterview tip: Warn about the classic bug: strpos() can return 0 (a valid position) which is falsy in loose comparisons. Always check with === false instead of if (!strpos(...)) to correctly detect 'not found'.
if (strpos($str, 'needle') === false) {
echo 'Not found';
}
Q8. How do you check if a value exists in an array? (in_array, array_search, array_key_exists)
| Function | Checks | Returns |
|---|---|---|
| in_array($needle, $arr) | Is this value present anywhere in the array? | true / false |
| array_search($needle, $arr) | Where is this value in the array? | The key if found, false if not |
| array_key_exists($key, $arr) | Does this specific key exist? | true / false |
$fruits = ['a' => 'Apple', 'b' => 'Banana'];
in_array('Banana', $fruits); // true
array_search('Banana', $fruits); // 'b'
array_key_exists('a', $fruits); // true
isset($fruits['c']); // false, also fails if value is nullInterview tip: Explain the difference between array_key_exists() and isset() for arrays: isset() returns false if the key exists but its value is null, while array_key_exists() correctly returns true in that case.
Q9. How do you remove duplicate values from an array in PHP?
Use array_unique() for simple scalar arrays, or a combination approach for arrays of associative sub-arrays where duplicates are defined by a specific field.
$nums = [1, 2, 2, 3, 3, 3];
$unique = array_unique($nums);
// [0 => 1, 1 => 2, 3 => 3] -- note: keys are preserved, gaps remain
$reindexed = array_values($unique);
// [1, 2, 3]For an array of associative arrays (e.g. removing duplicate users by email), array_unique() won't work directly since it compares whole (string-cast) values. Use array_column() plus array_unique() on the keys, or a manual loop:
$users = [
['id' => 1, 'email' => 'a@x.com'],
['id' => 2, 'email' => 'a@x.com'],
['id' => 3, 'email' => 'b@x.com'],
];
$unique = array_values(array_column($users, null, 'email'));
// keeps the last occurrence per unique emailInterview tip: Always mention that array_unique() preserves original keys, so pair it with array_values() if you need a clean sequential array afterward.
Q10. How do you format strings and numbers in PHP? (sprintf, number_format, str_pad)
| Function | Purpose | Example |
|---|---|---|
| sprintf($format, ...$args) | Build a formatted string using placeholders | sprintf('%05d', 42) = '00042' |
| number_format($num, $decimals) | Format a number with grouped thousands and fixed decimals | number_format(150000.5, 2) = '150,000.50' |
| str_pad($str, $len, $pad) | Pad a string to a certain length | str_pad('7', 3, '0', STR_PAD_LEFT) = '007' |
$price = 149999.999;
echo number_format($price, 2); // '150,000.00'
$orderId = 42;
echo sprintf('ORD-%04d', $orderId); // 'ORD-0042'Interview tip: A very practical follow-up: how would you generate invoice numbers like INV-000123? Answer: sprintf('INV-%06d', $id) or str_pad((string)$id, 6, '0', STR_PAD_LEFT).
Arrays & String Functions
Learn key PHP array and string manipulation methods. Essential for sorting, filtering, merging, and text processing in technical interviews.
What are the most commonly used array functions in PHP?
PHP has over 80 built-in array functions. These are the ones that come up most in day-to-day code and intervie...
What is the difference between array_map, array_filter, and array_reduce?
All three take a callback and an array, but they do fundamentally different things.FunctionPurposeReturnsarray...
How do you sort arrays in PHP? Explain sort, ksort, and usort.
Short Answer Indexed Arrays use numeric keys (starting from 0 by default) to store and access data. Associati...
What is the difference between explode() and implode() in PHP?
explode() splits a string into an array using a delimiter. implode() (alias: join()) joins array elements into...
What is the difference between array_merge() and the + operator for combining arrays?
Both combine two arrays, but they handle duplicate keys very differently.Aspectarray_merge()+ operatorString k...
What are the most useful PHP string functions? (strlen, substr, str_replace, trim)
FunctionPurposeExamplestrlen($str)Get string length in bytesstrlen('Hello') = 5substr($str, $start, $len)Extra...
What is the difference between strpos() and stripos()?
Both find the position of the first occurrence of a substring within a string. The only difference is case sen...
How do you check if a value exists in an array? (in_array, array_search, array_key_exists)
FunctionChecksReturnsin_array($needle, $arr)Is this value present anywhere in the array?true / falsearray_sear...
How do you remove duplicate values from an array in PHP?
Use array_unique() for simple scalar arrays, or a combination approach for arrays of associative sub-arrays wh...
How do you format strings and numbers in PHP? (sprintf, number_format, str_pad)
FunctionPurposeExamplesprintf($format, ...$args)Build a formatted string using placeholderssprintf('%05d', 42)...