AlexB
AlexB

Reputation: 45

How to remove specific number of elements from array

I have a function, which delete elements from array:

function remove_from_cart($prod_name,$price,$params,$count)
{

    $cart = array(
    "0"  => array ( 
    'name' => 'Bolognese - Small (26cm)',
    'params' => '',
    'price' => '12'),

    "1"  => array ( 
    'name' => 'Bolognese - Small (26cm)',
    'params' => '',
    'price' => '12')
    );

    $prod_arr = array(
    "name"=> $prod_name,
    "params"=> $params,
    "price" => $price);

    $count  = count( array_keys( $cart, $prod_arr ));

    while(($key = array_search($prod_arr, $cart)) !== false) {unset($cart[$key]);}

    return array('cart' => $cart, 'count' => $count);
}



$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);
//here is i want to remove just 1 of 2 elements

How to modify this function to have ability to set number of elements which i want to delete from array?

Thank you!

Upvotes: 1

Views: 56

Answers (1)

MorganFreeFarm
MorganFreeFarm

Reputation: 3733

Your example and question is not quite clear, but you can check this solution:

<?php

function remove_from_cart($prod_name,$price,$params,$count)
{

    $cart = array(
    "0"  => array (
    'name' => 'Bolognese - Small (26cm)',
    'params' => '',
    'price' => '12'),

    "1"  => array (
    'name' => 'Bolognese - Small (26cm)',
    'params' => '',
    'price' => '12'),

    "2"  => array (
    'name' => 'Bolognese - Small (26cm)',
    'params' => '',
    'price' => '12')
    );

    $prod_arr = array(
    "name"=> $prod_name,
    "params"=> $params,
    "price" => $price);

    $i = 0;

    while(($key = array_search($prod_arr, $cart)) !== false && $i < $count) {unset($cart[$key]); $i++;}

    return array('cart' => $cart, 'count' => $count);
}


$params = '';
$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);
var_dump($rem);

This would return two elements, because they are 3 elements and you pass 1 for $count if you pass 2, it would return 1 element:

Result for $rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1); :

array(2) { ["cart"]=> array(2) { [1]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(1) }

Result for $rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 2); :

array(2) { ["cart"]=> array(1) { [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(2) }

Upvotes: 1

Related Questions