Jump to content

Recommended Posts

How can I limit a foreach loop based on the value of an array. I tried something like this and it didn't work:

 

foreach($options as $key => $value)
	{
		if($key != 'sortby' || $key != 'sortdirection')
		{
			$this->db->where($key,$value);
		}
	}

 

This what I'm sending it:

array('lad_id' => $ladid, 'sortby' => 'score', 'sortdirection' => 'ASC')

 

I saw that I could do something like this:

array_slice($options, 0, 2)

 

However I wont know the numbers, I would like to limit it by the array values. Is there a way to do this?

 

Thank you.

 

Link to comment
https://forums.phpfreaks.com/topic/203963-limit-foreach-based-on-array-value/
Share on other sites

A callback function for array_walk is built that it takes one argument, and returns either true or false. It is built in the same manner as a regular function, but make sure it has an argument to it.

 

When the array_filter runs, it runs each element of the array against your function.

 

//Is first char a letter? suppose to be a number.
function letters($str) {
$str = substr($str,0,1);
if(!is_numeric($str)) return false;
return true;
}
//make an array;
$array = array('me','exercise','another','none','1dies');

//filter the array by our function;
$array1 = array_filter($array,'letters');

var_dump($array1);

 

On the other hand, array_walk passes both the key, and the value to a user defined function.

 

As in:

function letters($value,$key) {
$str = substr($key,0,1);
echo $str . ': ' . $value . "<br />\n";
return;
}
//make an array;
$array = array('me' => 'walking', 'fall' => 'exercise', 'taste' => 'another', 'three' => 'none', '14' => '1dies');

//filter the array by our function;
array_walk($array,'letters');

 

PS. don't bump, we see it.

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.