0

I have added few values in Wordpress option table like below:

option_name = optionLists

option_values = Option1, Option2, Option3, Option4

I retrieved those values using PHP like below:

$option_lists = get_option('optionLists');
$myOption = explode("," , $option_lists );

So, here $myOption is an array and if I print $myOption using print_r($myOption), it will show result like below:

Array ( [0] => Option1 [1] => Option2 [2] => Option3 [3] => Option4 )

Now, I want to delete one array element from the above array, say it is Option3. I wrote that like below:

$remvOption = array('4' => 'Option3');
$new_option = array_diff($myOption, $remvOption);

The expected output should be like below:

Array ( [0] => Option1 [1] => Option2 [3] => Option4 )

But, it is still showing:

Array ( [0] => Option1 [1] => Option2 [2] => Option3 [3] => Option4 )

May I know where I am doing the mistake? Thanks in advance.

1

1 Answer 1

0

Your code works for me.

But no need to have the ID of the item - just put the value itself

$myOption = array('Option1', 'Option2', 'Option3', 'Option4');
$remvOption = array('Option3');
$new_option = array_diff($myOption, $remvOption);

And then make sure you are printing the correct variable:

print_r($new_option);

This code gives me output:

 Array ( [0] => Option1 [1] => Option2 [3] => Option4 )
Sign up to request clarification or add additional context in comments.

5 Comments

array_diff() doesn't care about keys, so this doesn't really answer the question
@billyonecan - yes, you are correct, but it wont hurt to remove it either.
In $myOption variable the options are coming dynamically. I don't know how many options I have. So, I can't put value manually in array. I just made a string (Option1, Option2, Option3, Option4) value an array using explode function. I am just unable to do it when I am creating array using explode function. Manually it is possible and I know that. Thanks for your help but it is not the answer.
I only put that there as a demo to show the code works. You dont need to load 'myOption' first - you can do it in your example. My point is your code works as you have posted it. But you havent shown how you are printing the 'new option' - so my guess is you are doing it wrong somehow.
The mistake was in this code: $myOption = explode(",", $option_lists ); there will be a space after ',' inside the double quotation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.