Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

List out the checklist of array function is used in laravel inside foreach loop in laravel

When working with arrays in Laravel, you might commonly use various array functions inside a foreach loop. Here's a checklist of some commonly used array functions along with examples:

count()
foreach()
in_array()
array_key_exists()
array_map()
array_filter()
array_push()
array_slice()
array_sum()
array_unique

count() - Count the number of elements in an array:

$array = [1, 2, 3, 4, 5];
$count = count($array);
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode
$count = $data->count();
// OR
$count = count($data);
Enter fullscreen mode Exit fullscreen mode

foreach() - Iterate through each element in an array:

$fruits = ['apple', 'banana', 'orange'];
foreach ($fruits as $fruit) {
    // $fruit will be 'apple', 'banana', 'orange' in each iteration
}
Enter fullscreen mode Exit fullscreen mode

in_array() - Check if a value exists in an array:

wap to value present in array after converting table data using toarray()

$fruits = ['apple', 'banana', 'orange'];
if (in_array('banana', $fruits)) {
    // 'banana' is in the array
}
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode
$searchValue = 'some_value';
$exists = in_array($searchValue, $data->pluck('column_name')->toArray());
Enter fullscreen mode Exit fullscreen mode

array_key_exists() - Check if a key exists in an array:

$person = ['name' => 'John', 'age' => 30];
if (array_key_exists('name', $person)) {
    // 'name' key exists in the array
}
Enter fullscreen mode Exit fullscreen mode

array_map() - Apply a callback to each element of an array:

$numbers = [1, 2, 3];
$squaredNumbers = array_map(function($num) {
    return $num * $num;
}, $numbers);
Enter fullscreen mode Exit fullscreen mode
use Illuminate\Http\Request;

class YourController extends Controller
{
    public function processInputs(Request $request)
    {
        // Get all input values from the request
        $inputs = $request->all();

        // Define a custom callback function to append a prefix
        $appendPrefixCallback = function ($value) {
            return 'processed_' . $value;
        };

        // Use array_map with the custom callback
        $processedInputs = array_map($appendPrefixCallback, $inputs);

        // Do something with the processed inputs
        // For example, you can log the processed inputs
        \Log::info('Processed Inputs:', $processedInputs);

        // Your logic here...

        return redirect()->back()->with('success', 'Inputs processed successfully.');
    }
}
Enter fullscreen mode Exit fullscreen mode
use App\Models\User;
use App\Models\UserDetail;

class YourController extends Controller
{
    public function getUsersWithDetails()
    {
        // Retrieve users from the 'users' table
        $users = User::get();

        // Define a callback function to add additional details
        $addDetailsCallback = function ($user) {
            // Retrieve additional details from the 'user_details' table
            $userDetails = UserDetail::where('user_id', $user->id)->first();

            // Add additional details to the user object
            $user->additional_field = $userDetails ? $userDetails->additional_field : null;

            return $user;
        };

        // Use array_map with the custom callback
        $usersWithDetails = array_map($addDetailsCallback, $users->toArray());

        // Now $usersWithDetails contains users with additional details

        // Your logic here...

        return view('your_view', ['usersWithDetails' => $usersWithDetails]);
    }
}
Enter fullscreen mode Exit fullscreen mode
$mappedData = $data->map(function ($item) {
    // Apply some transformation to each item
    return $item->column_name;
});
Enter fullscreen mode Exit fullscreen mode

array_filter() - Filter elements of an array using a callback function:

wap to filter data after converting table data using toarray()

$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, function($num) {
    return $num % 2 == 0;
});
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode
$filteredData = $data->filter(function ($item) {
    // Apply some filtering condition
    return $item->column_name > 10;
});
Enter fullscreen mode Exit fullscreen mode

array_push() - Push one or more elements onto the end of an array:
wap to insert new data in table after converting table data using toarray

$stack = [1, 2, 3];
array_push($stack, 4, 5);
Enter fullscreen mode Exit fullscreen mode

array_merge() - Merge one or more arrays:

$array1 = ['a', 'b'];
$array2 = ['c', 'd'];
$mergedArray = array_merge($array1, $array2);
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Retrieve data from the database
$data = YourModel::all();

// Convert the collection to an array
$arrayData = $data->toArray();

// Add elements to the array using array_push
array_push($arrayData, 4, 5);

// Alternatively, you can use the push method directly on the collection
$data->push(4, 5);

// Output the modified array
dd($arrayData);
Enter fullscreen mode Exit fullscreen mode

array_slice() - Extract a slice of an array:

wap to get range of data after converting table data using toarray()

use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode
$numbers = [1, 2, 3, 4, 5];
$slicedArray = array_slice($numbers, 2, 2);
Enter fullscreen mode Exit fullscreen mode

$slicedData = $data->slice(0, 5); // Get the first 5 items
Enter fullscreen mode Exit fullscreen mode

array_search() - Search an array for a given value and return the corresponding key if successful:

$fruits = ['apple', 'banana', 'orange'];
$key = array_search('banana', $fruits);
Enter fullscreen mode Exit fullscreen mode
use App\Models\YourModel;

// Example: Using get() to retrieve data
$data = YourModel::get();

// Example: Using first() to retrieve a single record
$firstRecord = YourModel::first();

// Example: Using json_encode to encode data as JSON
$jsonEncodedData = YourModel::all()->toJson();
Enter fullscreen mode Exit fullscreen mode

These are just a few examples, and Laravel provides a rich set of array-related functions. Depending on your specific use case, you may also find functions like array_reduce(), array_column(), and others useful. Always refer to the official PHP documentation for a comprehensive list of array functions and their descriptions.

public function calculateTotalCost()
    {
        $shopping_cart = ["apple" => 1.0, "banana" => 0.5, "cherry" => 1.5, "date" => 0.75];
        $total_cost = array_sum($shopping_cart);

        return response()->json(['total_cost' => $total_cost]);
    }
Enter fullscreen mode Exit fullscreen mode
<?php
$originalArray = [1, 2, 3, 4, 2, 5, 6, 3, 7];

// Remove duplicate values
$uniqueArray = array_unique($originalArray);

// Print the resulting array
print_r($uniqueArray);
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)