0

Hi friends,

I want to delete an element from an array and re order the array ie

$myArray=array('a','b','c','d');

echo $myArray[1]; // print b;

I want to delete $myArray[1] From $ myArray and re order the array So that echo $myArray[1]; // Return c insted of b Thnaks In Advance
Rajeesh

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by Agarsia
0

I would create a function like this:

function deleteAndReorder($array,$index) {
 $length = count($array)-1;
 for($i=$index;$i<$length;$i++) {
  $array[$i] = $array[$i+1];
 }
 $array[$length] = "";
 return $array;
}

so you can get this:

$a = Array('a','b','c','d');
$a = deleteAndReorder($a,1);
echo $a[1];
1

Hi rajeesh_rsn,

Another option would be to do the following:

/* Original array */
$my_arr = array( "first","second","third","forth","fifth","sixth" );

/* Remove element from array */
$my_arr = remove_item_from_array( "third",$my_arr );

/* Display aletered array on screen */
print_r( $my_arr );

/* The function */
function remove_item_from_array($val,$arr) {
	/* Find value's index within the array */
	$index = array_search($val,$arr);
	/* Remove value */
	unset($arr[$index]);
	/* Return altered array with the first index reset to 0 */ 
	return array_values($arr);
}

Whichever solution you choose to use, I hope your project goes well.

Jim :)

Edited by jimforsyth: n/a

Votes + Comments
Useful post
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.