Skip to main content

Most common PHP array functions.

Most common PHP array functions.
 
PHP provides a wide range of array functions to manipulate and work with arrays. Here are some of the most commonly used array functions in PHP:

1. count: Returns the number of elements in an array.
$count = count($array);

2. array_merge: Combines multiple arrays into a single array,not for multidimensional array.
$result = array_merge($array1, $array2, ...);

$array1 = array('a', 'b', 'c');
$array2 = array(1 => 'd');

$resultArray = array_merge($array1, $array2);
print_r($resultArray);

Array ( [0] => a [1] => b [2] => c [3] => d )

3. array_push: Pushes one or more elements onto the end of an array.
array_push($array, $element1, $element2, ...);

  $multidimensionalArray = array(
    'colors' => array('red', 'green'),
    'fruits' => array('apple')
);

// Using array_push to add a new color to the 'colors' sub-array
array_push($multidimensionalArray['colors'], 'blue');

// Using array_push to add a new fruit to the 'fruits' sub-array
array_push($multidimensionalArray['fruits'], 'orange');

print_r($multidimensionalArray);

Array ( [colors] => Array ( [0] => red [1] => green [2] => blue ) [fruits] => Array ( [0] => apple [1] => orange ) )
 

4. array_pop: Removes and returns the last element from an array.
$lastElement = array_pop($array);

5. array_shift: Removes and returns the first element from an array.
$firstElement = array_shift($array);

$array = array('apple', 'banana');

$firstElement = array_shift($array);

echo "Removed Element: " . $firstElement . "\n";
print_r($array);

Removed Element: apple 
Array ( [0] => banana )

6. array_unshift: Adds one or more elements to the beginning of an array.
array_unshift($array, $element1, $element2, ...);

7. array_slice: Extracts a slice of an array.
$subset = array_slice($array, $start, $length);

8. array_splice: Removes a portion of the array and returns it.
$removed = array_splice($array, $start, $length);

$ms = array(
    'colors' => array('red', 'greenRemove', 'blue'),
);

// Remove 'green' from the 'colors' sub-array
array_splice($ms['colors'], 1, 1);
print_r($ms);
echo "<br />";
// Add 'purple' at index 1 in the 'colors' sub-array
array_splice($ms['colors'], 1, 1 , 'purple');

print_r($ms);

echo "<br />";
// Add 'purple' at index 1 in the 'colors' sub-array
array_splice($ms['colors'], 1 , 0  , 'ORANGE');

print_r($ms);

Array ( [colors] => Array ( [0] => red [1] => blue ) )
Array ( [colors] => Array ( [0] => red [1] => purple ) )
Array ( [colors] => Array ( [0] => red [1] => ORANGE [2] => purple ) )

9. array_key_exists: Checks if a key exists in an array.
if (array_key_exists($key, $array)) {
    // Key exists
}

10. in_array: Checks if a value exists in an array.
if (in_array($value, $array)) {
    // Value exists
}

11. array_search: Searches for a value in an array and returns its key.
$key = array_search($value, $array);

12. array_filter: Filters elements of an array using a callback function.
$filteredArray = array_filter($array, function($element) {
    return /* some condition */;
});

13. array_map: Applies a callback function to each element of an array.
$resultArray = array_map(function($element) {
    return /* some transformation */;
}, $array);

14. array_reduce: Reduces an array to a single value using a callback function.
$result = array_reduce($array, function($carry, $item) {
    return /* some reduction logic */;
});

These are just a few examples of the many array functions available in PHP. The PHP documentation is an excellent resource for exploring all available array functions and their use cases: PHP Array Functions.

Comments

Popular posts from this blog

MySQL's ACID compliance

Mysql acid compliance ACID is an acronym that stands for four key properties of database transactions: Atomicity Ensures that a transaction is treated as a single, indivisible unit of work Either all operations within a transaction are completed successfully, or none are If any part of the transaction fails, the entire transaction is rolled back to its previous state Prevents partial updates that could leave the database in an inconsistent state Consistency Guarantees that a transaction brings the database from one valid state to another valid state All data written to the database must adhere to defined rules, constraints, cascades, triggers, and other database integrity mechanisms Ensures that any transaction will not break the database's predefined rules Isolation Determines how and when changes made by one transaction become visible to other transactions Prevents interference between concurrent transactions MySQL provides different isolation levels: Read Uncommitted Read Commit...

PHP OOPs exercise - Basic Oops

  Here are key PHP OOP (Object-Oriented Programming) exercise questions with solutions: Basic Class and Object Exercise: // Create a simple bank account class class BankAccount {     private $accountNumber;     private $balance;     public function __construct($accountNumber, $initialBalance = 0) {         $this->accountNumber = $accountNumber;         $this->balance = $initialBalance;     }     public function deposit($amount) {         if ($amount > 0) {             $this->balance += $amount;             return true;         }         return false;  ...

Interview questions for Senior PHP Developer particle41.com

1.Self Introduction 2.Basic questions on session and cookie. 3.Where is session stored? 4.Difference between Cookie and session. 5.Will there be any session before session start? 6.Post Max execution time.How can we modify it? 7.We have a string, "BJFSJK".Without any php function reverse it with half the string length.   To reverse the string with half the string length without using any PHP functions, you can implement a simple algorithm to achieve the desired result. Here's how you can do it: Initialize two pointers, one at the beginning of the string and the other at the midpoint of the string. Swap characters between these two pointers iteratively, moving the pointers towards each other until they meet or cross each other. Here's the PHP code to implement this algorithm:  <?php $string = "ABC100"; $length = strlen($string); // Calculate the midpoint of the string $midpoint = (int)($length / 2); // Initialize pointers $start = 0; $end = $length - 1; //...