-3

I am removing an element from an array in PHP:

$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'no-image.jpg');
if (in_array('no-image.jpg', $images)) {
  $imgIndex = array_search('no-image.jpg', $images);
  array_splice($images, $imgIndex, 1);
}

And then I am checking to make sure the $images array isn't empty:

if (!empty($images)) {
  //Some code
}

But if my array only contains no-image.jpg and I remove it, will empty() return true or false?

ajarrow
  • 414
  • 2
  • 10

2 Answers2

0

Yes, your array will evaluate to empty. From the PHP manual:

The following values are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

So:

$images = array('no-image.jpg');
if (in_array('no-image.jpg', $images)) {
  $imgIndex = array_search('no-image.jpg', $images);
  array_splice($images, $imgIndex, 1);
}
echo var_dump(empty($arr)); //Will output bool(true)

And:

$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'no-image.jpg');
if (in_array('no-image.jpg', $images)) {
  $imgIndex = array_search('no-image.jpg', $images);
  array_splice($images, $imgIndex, 1);
}
echo var_dump(empty($arr)); //Will output bool(false)
ajarrow
  • 414
  • 2
  • 10
  • 1
    it's not usually a good idea to post questions that are just something you could/should try and then answer your own question - that's probably going to get you a lot of downvotes :-) – imposterSyndrome Sep 14 '20 at 11:29
  • @jameson2012, I've been helped a lot by question/answer posts that ask simple questions that can be easily figured out with a little testing and they weren't downvoted so I figured I'd pass the favor on :) – ajarrow Sep 14 '20 at 11:38
0

An aside - you could swap out the in_array, search and splice for a search and unset.

<?php    
$images = ['no-image.jpg'];
$imgIndex = array_search('no-image.jpg', $images);
if($imgIndex !== false) {
    unset($images[$imgIndex]);
}

var_dump($images);
var_dump(empty($images));

Output:

array(0) {
}
bool(true)

You can use unset, if you don't care for the re-indexing that array_splice affords you.

Progrock
  • 7,373
  • 1
  • 19
  • 25
  • I actually chose array_splice because I need the array to be reindexed – ajarrow Sep 14 '20 at 15:00
  • Fair enough, you may get minor performance gains with an equivalent unset followed by array_values. But you can still drop the in_array followed by array_search for just the array_search. Negligible gains. – Progrock Sep 14 '20 at 15:04