How to Checks if a value exists in an Array (PHP)

In this article i want to share to you how to check a value is exists in an Array. I found some PHP tricks to resolve my problem.

I have this code in my PHP sourcecode :

foreach ($x_waktu as $value) {
if (in_array($waktu, (explode(',',$value)))){
//what will you do
}
}

I will explain one by one until you understand how to check a value is exists in an your array. On this code we have three variable:

- $x_waktu, $value and $waktu

Variable $x_waktu is some array with value {1,2,3) then $waktu is string variable with random data, and the last variable is $value. $value is variable that will be used to extract an array value by indexs. You can use foreach to extract value array to other variable or use the value to something else, but in my code i use the value to converted to an array.

Then how to checks if a value exists in an array?


So you will use PHP function "in_array()" to resolve your problem. This function have two parameter, first parameter is "The searched value" and seccond parameter is "your data array". And then you can use explode function to coonverted string value to array value.

Always remember, the PHP function explode lets you take a string and blow it up into smaller pieces. Php explode - (Split string by string).
Previous
Next Post »