Jump to content

Limit foreach based on array value?


piznac

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.