Dean Lark
Dean Lark

Reputation: 11

Loop through foreach array

I'm having a problem looping through my array to get just one value each time. I want to gray only 1 value because I'm calling that value in jquery. I'm new and sorry if this is too basic but I've been trying for days, pulling my hair out!

$designslist = array('design1','design2','design3','design4');
$current_index = 0;
$current_id = current($designslist);
$next = $designslist[$current_index + 1];

foreach( $designslist as $value )
{
  if( $value !== $next )continue;
  $nexts =  $next;
  echo $nexts;
  $current_index++;
}

Inside my html

<a href="#" id="<?php echo $nexts; ?>">next</a>

calling the id with jquery

$('#design1').on('click',function() {
  $('#web1').removeClass().addClass('big1');
});

Upvotes: 1

Views: 133

Answers (3)

Eduardo Russo
Eduardo Russo

Reputation: 4219

Ok, you seem to be mixing for with foreach using these "current_id" and "next" variables.

You can use this kind of foreach statement:

foreach ($designList as $key => $value) {
    echo "The key of $value is $key";
}

As you want to return only unique values, you should use the "array_unique" function. Try this:

foreach (array_unique($designList) as $key => $value) {
    echo "The key of $value is $key";
}

I know it's not related to the question, but, as you said you're new to this, there are some PHP tips you should follow.

You're mixing snake_case with camelCase in your variables. I recommend using camelCase, but it's up to you.

Upvotes: 0

crafter
crafter

Reputation: 6296

You can try array search

$tag       = array_search($value, $designslist);
$nexts     = $$designslist[$tag]; 

Upvotes: 0

Onimusha
Onimusha

Reputation: 3385

foreach( $designslist as $value )

needs to be

foreach( $designslist as $i => $value )

$i is the array index

Upvotes: 2

Related Questions