array walk

How to run loop without using for or foreach loop over array

I use to contribute source code in few website, in that website one person asked question how to run the loop without using loop in array. On that time it’s trigger on my mind is array_walk function which can surface key and value without running loops.

So let’s walk-though the code

<?php
//create the array with 10 elements
$arrData = array(1,2,3,4,5,6,7,8,9,10);


//create a function which will surface our data
function surefaceData($value,$key)
{
	echo $key.'->'.$value;
	echo '<br />';
}


//now will call the function array_walk function
array_walk($arrData,'surefaceData');

First parameter is array which will walk-though the entire array regardless of pointer position.
Second parameter is callback, where we have called surefaceData function.

Value is the first parameter and key is the second parameter in surefaceData function.
If you want you can also add userData parameter which will display prefix value like below.

<?php
//create the array with 10 elements
$arrData = array(1,2,3,4,5,6,7,8,9,10);
 
 
//create a function which will surface our data with prefix
function surefaceData($value,$key,$prefix)
{
	echo $prefix.'--'.$key.'->'.$value;
	echo '<br />';
}
 
 
//now will call the function array_walk with third parameter userData
array_walk($arrData,'surefaceData','myData');