piyusharora420 Posted May 25, 2012 Share Posted May 25, 2012 Hello, I am trying to make a program for adding an element at the beginning of an array. I know it is possible with array_unshift. But, I want to create a function myself for serving the purpose. I tried a lot but no success. Please go through the below code and find out the wrong or post your own code. Thanks. <?php function addstart($array,$v) { $s=$array[0]; for($i=0;$i<5;$i++) { $s=$array[i+1]; $array[i+1]=$array[i];$array[i]=$s; } $array[0]=$v; print_r($array); } $x=888; $arr=array(1,2,8,96,85); addstart($arr,; //print_r($arr); ?> Quote Link to comment https://forums.phpfreaks.com/topic/263111-add-an-element-to-array-without-using-build-in-function/ Share on other sites More sharing options...
PravinS Posted May 25, 2012 Share Posted May 25, 2012 Use this function <?php function addstart($array=array(),$newval) { $new_array = array(); $new_array[0] = $newval; if (is_array($array)) { foreach($array as $key => $value) { $new_array[] = $value; } } return $new_array; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/263111-add-an-element-to-array-without-using-build-in-function/#findComment-1348557 Share on other sites More sharing options...
piyusharora420 Posted May 28, 2012 Author Share Posted May 28, 2012 Thanks alot pbs. Quote Link to comment https://forums.phpfreaks.com/topic/263111-add-an-element-to-array-without-using-build-in-function/#findComment-1349192 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.