views:

158

answers:

3

How to find a value exist in an array and how to remove it. If any php builtin array functions for doing this. After removing I need the sequential index order. any body knows please help me.

+3  A: 

You need to find the key of the array first, this can be done using array_search()

Once done, use the unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>
Kerry
This is the resultArray ( [0] => apple [1] => orange [2] => pear [3] => green ) Warning: Wrong parameter count for array_search() in C:\wamp\www\test\test.php on line 5Array ( [0] => apple [1] => orange [2] => pear [3] => green )
learner
@learner the haystack argument was missing in http://de3.php.net/manual/en/function.array-search.php - the manual is your friend.
Gordon
yes.this will work $array = array( 'apple', 'orange', 'pear', 'green' );unset($array[array_search('orange', $array)]);but the array sequence is missing. How to correct that
learner
What do you mean the sequence is missing? What sequence should it be in?
Kerry
array index is 0 2 3 4 is now 1 is missing I need it like 0 1 2 4.. etc
learner
also it has one another pbm if the search value not there array_search() function return false. it will cause the removal of 0th index value :(
learner
Then test the value before you remove it `$key = array_search( 'value' );` And not to take the credit, but to reindex arrays, see here: http://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php
Kerry
+1  A: 

To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:

<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');

print_r($hackers);

// Search
$pos = array_search('Linus Trovalds', $hackers);

echo 'Linus Trovalds found at: ' . $pos;

// Remove from array
unset($hackers[$pos]);

print_r($hackers);
?>

You can refer: http://www.php.net/manual/en/ref.array.php for more array related functions.

mohitsoni
+1  A: 

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>

Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-

<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>

Hope it helps.

Knowledge Craving