Jump to content

Recommended Posts

I have a couple quick array questions:

 

First: How do you echo the array index value? I'm using the following code:

foreach($_SESSION['box'] as $CartItem[]=>$items)
{
foreach($items as $key => $item)
	{
            if($key) 
		{
			$class = 'order'.++$key;
		}
		else
		{
			$class = 'order';
		}
		echo "<div class='$class'>$item</div>";
	}
}

 

I would like to be able to delete an individual array element using this reference but I do not know how to display this. I want the value of, for example:

$_SESSION['box'][3], but don't know how to echo the 3.

 

Second, Is there a function that resets all array index values back to "normal" after deleting any array element using unset(). For example:

I have the array with values in 0, 1, 2, 3, 4 and I delete index value 3 so my array is than 0, 1, 2, 4. Is there a function to change this to: 0, 1, 2, 3 ???

Link to comment
https://forums.phpfreaks.com/topic/69728-solved-couple-array-questions/
Share on other sites

try

<?php
session_start();

// generate testing value
if (count($_SESSION['box']) == 0) $_SESSION['box'] =array(array('1-1','1-2'), array('2-1', '2-2', '2-3'), array('3-1', '3-2'), array('4-1'));

if (count($_POST)) 
foreach ($_POST as $key => $v) 
	if ($v == 'Delete' and array_key_exists($_SESSION['box'][$key])) 
		unset($_SESSION['box'][$key]);

$_SESSION['box'] = array_values($_SESSION['box']); // reorganize array keys
// try to refresh page !

echo '<form method="POST">';
foreach($_SESSION['box'] as $CartItem=>$items) {
foreach($items as $key => $item) echo '<div class="class'. ($key + 1) . '">'.$item.'</div>';
echo '<input type="submit" name="' . $CartItem . '" value="Delete" /><hr />';
}
// for testing
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>

Thanks for the help!

 

I get the following warning and it does not remove the row:

 

Warning: Wrong parameter count for array_key_exists() on line 10

 

line 10 refers to:

 

if ($v == 'Delete' and array_key_exists($_SESSION['box'][$key]))

 

I'm pretty new at this so I'm not sure what to do.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.