Khalid Khalid - 7 months ago 12
PHP Question

How to check availablity of each seprated string in array?

I have a string with pipe symbol | where i need to check each piped value is contain in the $attrib array

so if the each value is present show success or show error.


PHP


<?php

$fields = "NAME|PHONE|EMAIL";
$get_each_val = expolde('|',$fields)

$attribs = array
(
"NAME" => "Jony",
"EMAIL" => "jonyJoe@abc.com",
"LOCATION" => "Xyz",
"ADDRESS" => "23 Street",
"MESSAGE" => "Hi there!"
);

//need to check

if $get_each_val // exploded from $fields

contain in

array_keys($attribs)

if
//$get_each_val is present in $attribs

echo $get_each_val.' - success<br/>';
else
echo $get_each_val.' - error <br/>';

?>

OUTPUT LIKE:

NAME - success
PHONE - error
EMAIL - success

Answer

You can use the following code:

<?php
  $fields  = "NAME|PHONE|EMAIL";
   $get_each_val = explode('|',$fields);

  $attribs = array
 (
   "NAME"=> "Jony",
   "EMAIL"=> "jonyJoe@abc.com",
   "LOCATION"=> "Xyz",
   "ADDRESS"=> "23 Street",
   "MESSAGE"=> "Hi there!"
 );
    foreach ($get_each_val as $value) {

 if(isset($attribs[$value]))
 {
       echo $value.' - success<br/>';
  }
  else
  {
     echo  $value.' - error <br/>';
  }
}
 ?>