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

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];

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 :)

commented: Useful post +6

Unset the value is simpler and neat.

yes sorry, I forgot this function xD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.