Jump to content

How Can I Accomplish This (Find and Compare)?


chaseman

Recommended Posts

Let's say for example I have 3 ID's in ONE database row like this:

     

name:values:

page ids17 23 32

 

And I have a list of page titles with the ID's of the pages inserted into the value field of a checkbox.

 

[] page title 1

[] page title 2

[] page title 3

[] page title 4

[] page title 5

[] page title 6

 

What I Want to Do!

I want to fetch the page ID's from the database and I want a way to see if there match any page ID's from the list with the page ID's from the database row. Based on that I want to run an if statement. How can I do that?

 

The string of ID's from the database would be the haystack, and the ID's from the list would be the needles, and every time one ID from the haystack matches with an ID from the list then that page title should be automatically marked as checked with the help of an if statement.

 

 

This is how the list gets listed, with a foreach loop:

 

<?php 
  $pages = get_pages(); 
  foreach ($pages as $pagg) {
  	$option = '<input type="checkbox" name="exclude[]" value="'. $pagg->ID .'">';
$option .= $pagg->post_title . "<br />";
echo $option;
  }
?>

 

Now I need to compare the ID in the value field with the ID string (separated by spaces) in the database row, and when a match occurs then execute a case.

 

I know there are functions like str_replace and similar, but I'm not sure if I can do that with them, what would be a fitting function for my case?

 

Link to comment
Share on other sites

You can use explode to split the string from the DB into an array of IDs at the spaces. Then use in_array on the array of ids to check if the pages id is in the list.

 

<?php
$ids = explode(' ', '17 23 32');

if(in_array($pagg->ID, $ids))
echo 'Page ID is in the ids list.';
else
echo 'Page ID is not in the ids list.';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.