Jump to content

add an element to array without using build in function


piyusharora420

Recommended Posts

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);
?>

Link to comment
Share on other sites

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;
}
?>

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.